还在用满屏try...catch异常?

点赞再看,养成习惯,大家好,我是辰兮!今天介绍怎么解决冗余的try...catch异常

目录

1、开场白

2、介绍

3、总结


开场白

今天公司来了一位新主管铁蛋儿,新官上任三把火嘛,这等好事肯定是得我们来承担啦

铁蛋儿看了看我们项目代码,还没半分钟,骂人的话直接脱口而出:“XXXXXXXXX,是谁写的这串破代码啊,全都是try...catch,看得我头都疼了,赶紧改掉!!”


介绍

在我们开发接口的时候,如果有报错没做处理是不是会发生这种事情:

@RequestMapping("/hello")
@RestController
public class HelloController{

    @GetMapping("/test")
    public String test() {
        int result = 100 / 0;
        return "success";
    }
}

访问接口时直接报错:

 这岂不是栓Q了,用户直接可以看到我们报错信息,为了解决这个问题,通常会加一个try...catch

@GetMapping("/test")
public String test() {
    String result = "success";
    try {
        int addUser = 100 / 0;
    } catch (Exception e) {
        result = "数据解析异常";
    }
    return result;
}

在访问之后如果有异常会给一个报错信息,看起来是挺不错的

但是!!!一个接口这样写还好,那一百个呢?一千个呢??这样写也好吗?

答案肯定是否定的,这时全局异常处理的注解就派上用场了:@RestControllerAdvice

@ControllerAdvice
public class ExceptionManage {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionManage.class);

    /**
     * 处理 @RequestBody参数校验异常
     *
     * @param e
     * @return
     */

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> ExceptionHandler(Exception e) {
        LOGGER.error("未知异常", e);
        String errorMsg = "UnExcepted Error:" + e.getMessage();
        return new ResponseEntity<>(new ResponseData(false, "G_0500", errorMsg), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<?> ServiceExceptionHandler(Exception e) {
        LOGGER.error("服务异常", e);
        String errorMsg = "UnExcepted Error:" + e.getMessage();
        return new ResponseEntity<>(new ResponseData(false, "G_0500", errorMsg), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<?> handleAuthenticationException(AuthenticationException e) {
        LOGGER.error("授权异常", e);
        return new ResponseEntity<>(new ResponseData(false, "G_401", "Authentication Error:" + e.getMessage()), HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(DataFormatException.class)
    public ResponseEntity<?> handleDataFormatException(DataFormatException e) {
        LOGGER.error("数据解析异常", e);
        return new ResponseEntity<>(new ResponseData(false, "G_401", "Parse Data Error:" + e.getMessage()), HttpStatus.BAD_REQUEST);
    }

}

只需在handleException方法中处理异常情况,业务接口中可以放心使用,不再需要捕获异常(有人统一处理了)。那岂不是爽歪歪?

总结

在try...catch很多的情况下用@RestControllerAdvice来配合使用会比较方便。

猜你喜欢

转载自blog.csdn.net/ke2602060221/article/details/126247590