@ControllerAdvice + @ExceptionHandler 处理 全部Controller层异常

时间:2022-05-06
本文章向大家介绍@ControllerAdvice + @ExceptionHandler 处理 全部Controller层异常,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚。

如此一来,我们的 Controller 层就不得不进行 try-catch Service 层的异常,否则会返回一些不友好的错误信息到客户端。但是,Controller 层每个方法体都写一些模板化的 try-catch 的代码,很难看也难维护,特别是还需要对 Service 层的不同异常进行不同处理的时候。例如以下 Controller 方法代码(非常难看且冗余):

    @PostMapping("/uppic1")
    @ResponseBody
    public JsonResponse uppic1(@RequestParam("file1") MultipartFile file1) throws Exception {
        JsonResponse jr=null;
        FastDFSClient client = new FastDFSClient(fdfs_client);
        String extName = file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf(".")+1);
        String path = null;
        try {
            path = client.uploadFile(file1.getBytes(),extName,null);
            jr=new JsonResponse(1,"操作成功",file_server+path);
        } catch (Exception e) {
            jr=new JsonResponse(0,"操作失败",path);
            e.printStackTrace();
        }
        return jr;
    }

使用ControllerAdvice :

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    JsonResponse handleException(){
        JsonResponse jr=new JsonResponse(1,"服务器异常!");
        return jr;
    }
}

这样所有controller层的异常都会返回这样的提示了。