SpringMVC_异常统一处理

本文介绍了如何在SpringMVC项目中实现全局统一异常处理,包括使用@ControllerAdvice进行控制器增强,以及如何使用@ExceptionHandler处理不同类型的异常,如ArithmeticException、业务异常、持久层异常和系统异常。
摘要由CSDN通过智能技术生成

3.全局统一异常处理

3.1目前存在问题

  • 模拟后台出现服务器异常

    @GetMapping
        public ResultResp list(@RequestParam(required = false) String name){
            System.out.println(1/0);
            List<Item> ret = service.lists(name);
            return ResultResp.success(ret==null?Code.PAGE_FAIL:Code.PAGE_OK,ret);
        }
    
  • 出现如下错误

    在这里插入图片描述

3.2后端服务可能会出现的异常

  • 框架可能报错

  • 持久层代码报错

  • 业务层业务代码报错

  • 控制层业务代码报错

  • 注意:这些异常不能避免的,此时应该把所有的异常在表现层进行统一的处理(aop)

  • 解决方案

    @RestControllerAdvice
    public class ExceptionHandlerController {
    
        @ExceptionHandler(ArithmeticException.class)
        public ResultResp handlerException(){
            System.out.println("出现异常了");
            return new ResultResp(500,null,"服务繁忙,请稍后再试");
        }
    }
    

3.3@RestControllerAdvice

  • 使用来做控制器增强操作

    名称@RestControllerAdvice
    位置Rest 风格增强类上
    作用给控制器做增强操作
    使用类上面
    • 包含了如下注解
      • @ResponseBody
      • @ControllerAdvice
      • @Component

3.4@ExceptionHandler

  • 异常处理器

    名称@ExceptionHandler
    位置方法上
    属性具体的异常类型
    作用处理具体异常的,设定具体异常类型,出现异常后,终止controller中方法的执行,转入当前方法执行

3.5项目中具体处理

  • 业务异常

    @Data
    public class BusinessException extends RuntimeException{
        private Integer code;
    }
    
  • 持久层异常

    @Data
    public class DaoException extends RuntimeException{
        private Integer code;
    }
    
  • 系统异常

    @Data
    public class SystemException extends RuntimeException{
        private Integer code;
    }
    
  • 其它异常

    @Data
    public class OtherException extends RuntimeException{
        private Integer code;
    }
    
    
  • 定义code

    public class Code {
        /**
         * 定义好协议之后,前端和后端统一按照协议执行
         */
        public static final Integer SAVE_OK = 20000;
        public static final Integer SAVE_FAIL = 20001;
    
    
        public static final Integer UPDATE_OK = 20010;
        public static final Integer UPDATE_FAIL = 20011;
    
        public static final Integer DELETE_OK = 20020;
        public static final Integer DELETE_FAIL = 20021;
    
        public static final Integer GET_OK = 20030;
        public static final Integer GET_FAIL = 20031;
    
        public static final Integer PAGE_OK = 20040;
        public static final Integer PAGE_FAIL = 20041;
    
        
        public static final Integer BUSINESS_ERR = 50001;
        public static final Integer SYSTEM_ERR = 50002;
        public static final Integer DAO_ERR = 50003;
        public static final Integer OTHER_ERR = 50005;
        
        
    
    }
    
  • 统一异常处理

    @RestControllerAdvice
    public class ExceptionHandlerController {
        //业务异常的例子:账户名和密码错误
        @ExceptionHandler(BusinessException.class)
        public ResultResp handlerBusinessException(BusinessException e){
            return new ResultResp(e.getCode(),null,e.getMessage());
        }
        
        //需要发送短信提醒运维人员
        @ExceptionHandler(SystemException.class)
        public ResultResp handlerSystemException(SystemException e){
            //发送短信提醒业务人员的操作
            //日志打印
            return new ResultResp(e.getCode(),null,e.getMessage());
        }
    
        @ExceptionHandler(OtherException.class)
        public ResultResp handlerException(OtherException e){
            return new ResultResp(e.getCode(),null,e.getMessage());
        }
    }
    
  • 控制层方法

     @GetMapping
    public ResultResp list(@RequestParam(required = false) String name) {
        if (name == null || name.equals(""))
            throw new BusinessException(Code.BUSINESS_ERR,"传参不正常请重试");
        List<Item> ret = null;
        try {
            ret = service.lists(name);
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_ERR,"系统繁忙,请稍后再试");
        }
        return ResultResp.success(ret == null ? Code.PAGE_FAIL : Code.PAGE_OK, ret);
    }
    
Spring MVC 中,我们可以通过实现一个异常处理器来统一处理控制器抛出的异常。具体步骤如下: 1. 实现一个异常处理器类,并添加 @ControllerAdvice 注解。 2. 在异常处理器类中定义处理不同类型异常的方法,并使用 @ExceptionHandler 注解标记。 3. 在方法中编写异常处理逻辑,例如将异常信息记录到日志中、返回错误信息等。 4. 如果需要返回 JSON 格式的错误信息,可以使用 @ResponseBody 注解。 以下是一个简单的示例: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> handleException(Exception e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "500"); errorMap.put("message", e.getMessage()); return errorMap; } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public Map<String, Object> handleValidationException(MethodArgumentNotValidException e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "400"); errorMap.put("message", "参数校验失败"); List<String> errors = e.getBindingResult() .getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList()); errorMap.put("errors", errors); return errorMap; } } ``` 在上述示例中,我们定义了两个处理异常的方法:handleException 和 handleValidationException。handleException 方法处理所有未被其他方法处理异常,返回一个包含错误码和错误信息的 Map 对象;handleValidationException 方法处理参数校验失败的异常,并将校验失败的所有错误信息返回。 最后,需要注意的是,如果同时存在多个异常处理方法,Spring MVC 会按照异常类型匹配最合适的处理方法。如果没有找到合适的处理方法,则会将异常抛给 Servlet 容器进行处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值