异常类的使用
1、对 Exception 的两种处理方式
Controller以及RestController分别对应着 ModelAndView 以及 Json,所以我们应当对Exception的处理做两手准备,分别是针对Controller的 error.ftl 以及 针对RestController 的 FrontVO。两者的实现方式具体可参见代码 FileSys的springboot分支。
2、简要代码如下
@GetMapping("/list")
public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size,
Map<String, Object> map) {
PageRequest request = PageRequest.of(page - 1, size);
Page<FileMdata> fileMdataPage = fileMdataService.findList(request);
if (fileMdataPage == null) {
map.put("msg", ResponseCode.DATABASE_EMPTY.getMsg());
map.put("url", "/list");
return new ModelAndView("common/error", map);
}
map.put("fileMdataPage", fileMdataPage);
map.put("currentPage", page);
map.put("size", size);
return new ModelAndView("file/list", map);
}
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(MultipartFile file, String size) {
String mdata = null;
try {
mdata = fileService.save(file.getInputStream(), Integer.parseInt(size));
} catch (NumberFormatException | IOException e) {
throw new FileCRUDException(ResponseCode.SYSTEM_ERROR);
}
String info = fileMdataService.add(JsonUtil.parseJson(mdata, FileMdata.class));
return info;
}