Spring|@ExceptionHandler

捕获系统中未被catch的异常,统一返回给用户。

自定义异常类:

public class CdaException extends RuntimeException {

    private static final long serialVersionUID = 8461347797506225533L;

    public CdaException() {
    }

    public CdaException(String errorMsg) {
        super(errorMsg);
    }

    public CdaException(Exception ex){
        super(ex);
    }
}

统一异常处理:

@ControllerAdvice
@Component
public class GlobalExceptionHandler {

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

    /**
     * 判断错误是否是已定义的已知错误,不是则由未知错误代替,同时记录在log中
     *
     * @param ex 异常
     * @return 错误内容
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionGet(Exception ex, HttpServletRequest request) {
        LOGGER.error("【系统异常】请求uri:[{}]", request.getRequestURI(), ex);

        // 项目自定义异常
        if(ex instanceof CdaException){
            CdaException cdaException = (CdaException) ex;
            return ResultGenerator.genServerErrorResult(cdaException.getMessage());
        }

        //权限异常

        //...

        return ResultGenerator.genServerErrorResult(ex.getMessage());
    }
}


@ControllerAdvice、@RestControllerAdvice:Controller的增强注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping、@GetMapping注解中。

原文地址:https://www.cnblogs.com/maikucha/p/14043883.html