springboot全局异常捕获

本文最后更新于1 分钟前,文中所描述的信息可能已发生改变。

Springboot全局异常捕获设置

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Log LOG = LogFactory.getLog(GlobalExceptionHandler.class);

    /**
     * 实体类设置的message异常信息的处理
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public CommonResult<?> BindingExceptionHandler(BindException e) {
        LOG.error("绑定值异常:【"+e.getBindingResult().getFieldError().getDefaultMessage()+"】");
        return new CommonResult().error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * http请求的方法不正确
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public CommonResult<?> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
        LOG.error("http请求的方法不正确:【"+e.getMessage()+"】");
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }

    /**
     * 请求参数不全
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public CommonResult<?> missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        LOG.error("请求参数不全:【"+e.getMessage()+"】");
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }

    /**
     * 请求参数类型不正确
     */
    @ExceptionHandler(TypeMismatchException.class)
    @ResponseBody
    public CommonResult<?> typeMismatchExceptionHandler(TypeMismatchException e) {
        LOG.error("请求参数类型不正确:【"+e.getMessage()+"】");
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }

    /**
     * 数据格式不正确
     */
    @ExceptionHandler(DataFormatException.class)
    @ResponseBody
    public CommonResult<?> dataFormatExceptionHandler(DataFormatException e) {
        LOG.error("数据格式不正确:【"+e.getMessage()+"】");
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }

    /**
     * 非法输入
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public CommonResult<?> illegalArgumentExceptionHandler(IllegalArgumentException e) {
        LOG.error("非法输入:【"+e.getMessage()+"】");
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }

    @ExceptionHandler  //处理其他异常
    @ResponseBody
    public CommonResult<?> allExceptionHandler(Exception e){
        LOG.error("具体错误信息:【"+e.getMessage()+"】"); //会记录出错的代码行等具体信息
        int count = 0; //只打印15行的错误堆栈
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            LOG.error(stackTraceElement.toString());
            if(count++ > 13) break;
        }
        return new CommonResult().error("http请求的方法不正确:【"+e.getMessage()+"】");
    }
}

@ControllerAdvice是一个springMVC的类增强注解,springMVC的异常处理机制,当controller层出现异常时,会进入到@ControllerAdvice注解的类进行处理,@ControllerAdvice注解的类中可以定义多个@ExceptionHandler注解的方法来处理不同的异常。

git提交了敏感信息如何回滚
和谁都能聊得来