@RestControllerAdvice注解 @ExceptionHandler注解

发布时间 2023-04-16 14:40:23作者: xiaoovo

RestControllerAdvice+ExceptionHandler这两个注解的组合,被用作项目的全局异常处理。一旦项目中发生了异常,就会进入使用了RestControllerAdvice注解类中使用了ExceptionHandler注解的方法。
下面是一些项目全局异常的处理

@ControllerAdvice(annotations = {RestController.class, Controller.class} )
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> excptionHandler(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        String message = e.getMessage();
        String[] s = message.split(" ");
        if (message.contains("Duplicate")){
            return R.error(s[2]+"already exists");
        }
        return R.error("false");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> excptionHandler(CustomException e){
        log.error(e.getMessage());

        return R.error(e.getMessage());
    }
}
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespBean ExceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException exception = (GlobalException) e;
            return RespBean.error(exception.getRespBeanEnum());
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBean.setMessage("参数校验异常:" + bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        System.out.println("异常信息" + e);
        return RespBean.error(RespBeanEnum.ERROR);
    }
}