zoukankan      html  css  js  c++  java
  • @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层的异常都会返回这样的提示了。

  • 相关阅读:
    输入输出重定向
    MarkdownPad 2中编辑
    (转)Maven最佳实践:划分模块
    (转)maven设置内存
    我收集的sonar参考资料
    (转)linux service理解
    制作service服务,shell脚本小例子(来自网络)
    6
    4
    5
  • 原文地址:https://www.cnblogs.com/jiangwz/p/8589506.html
Copyright © 2011-2022 走看看