springboot全局统一异常处理

配置文件:

spring:
  # 出现错误时, 直接抛出异常
  mvc:
    throw-exception-if-no-handler-found: true
  # 不要为工程中的资源文件建立映射
  resources:
    add-mappings: false

添加配置文件的原因是需要捕获404异常

统一处理类

import com.jesse.bean.ResponseResult;
import com.jesse.exception.BasicException;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常控制类
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 404异常处理
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public ResponseResult errorHandler(NoHandlerFoundException exception) {
        return new ResponseResult("404",exception.getMessage(),null);
    }

    /**
     * 405异常处理
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResponseResult errorHandler(HttpRequestMethodNotSupportedException exception) {
        return new ResponseResult("405",exception.getMessage(),null);
    }

    /**
     * 415异常处理
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public ResponseResult errorHandler(HttpMediaTypeNotSupportedException exception) {
        return new ResponseResult("415",exception.getMessage(),null);
    }

    /**
     * 500异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult errorHandler (Exception exception) {
        return new ResponseResult("500",exception.getMessage(),null);
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(value = BasicException.class)
    @ResponseBody
    private ResponseResult errorHandler (BasicException exception) {
        return new ResponseResult(exception.getCode(),exception.getMessage(),null);
    }
}

返回的Bean

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult {
    private String code;
    private String msg;
    private Object data;
}

参考资料:
https://www.cnblogs.com/bndong/p/10135370.html

你可能感兴趣的:(springboot全局统一异常处理)