全局异常处理类

/**
 * @Author:humorchen
 * @Date 2020/11/6 10:46
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static final Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 无权访问
     */
    @ExceptionHandler(NoAuthAccessException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R handleNoAuthAccessException(NoAuthAccessException exception){
        logger.error(exception.getMessage());
        return new R().error(exception.getMessage());
    }
    /**
     * 缺少请求参数错误
     * @param exception
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleMissingReqParaException(MissingServletRequestParameterException exception){
        logger.error("缺少请求参数",exception.getMessage());
        return new R().error("缺少请求参数","MissingParameters");
    }
    /**
     * 数据格式错误
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleMissingReqParaException(HttpMessageNotReadableException exception){
        logger.error("数据格式错误",exception.getMessage());
        return new R().error("数据格式错误","IllegalPayloadError");
    }

    /**
     * 请求方式不允许 MethodNotAllowed
     * @param exception
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(value = HttpStatus.METHOD_NOT_ALLOWED)
    public R handleMethodNotAllowedException(HttpRequestMethodNotSupportedException exception){
        logger.error("请求方式不允许",exception.getMessage());
        return new R().error("请求方式不允许","MethodNotAllowed");
    }

    /**
     * 空指针错误
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleNullPointerException(NullPointerException exception){
        logger.error("请求数据不完整",exception.getMessage());
        return new R().error("请求数据不完整","NullPointException");
    }

    /**
     * 错误默认返回
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleException(Exception exception){
        logger.error("请求失败",exception.getStackTrace());
        return new R().error("请求失败","Exception");
    }
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleException(RuntimeException exception){
        logger.error("执行出错",exception.getStackTrace());
        return new R().error("执行出错","RuntimeException");
    }
}

R是我的一个结果返回的包装类

/**
 * 结果包装类
 * @Author:humorchen
 * @Date 2020/11/5 15:19
 */

public class R<T> implements Serializable {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    private String msg="";
    private String code="";
    private static final String SUCCESS="Success";
    private static final String ERROR="Error";
    private T data;
    public R(){

    }
    public R<T> success(String msg){
        this.msg=msg;
        this.code=SUCCESS;
        logger.info(msg);
        return this;
    }
    public R<T> success(String msg, T data){
        this.msg=msg;
        this.data=data;
        this.code=SUCCESS;
        logger.info(msg,data);
        return this;
    }
    public R<T> error(String msg){
        this.msg=msg;
        this.code=ERROR;
        logger.error(msg);
        return this;
    }
    public R<T> error(String msg, String code){
        this.msg=msg;
        this.code=code;
        logger.error(msg,code);
        return this;
    }
//    public Ret(String msg, String code){
//        this.msg=msg;
//        this.code=code;
//    }
    public R(T data){
        if(data==null){
            this.code=ERROR;
            this.msg="请求失败(无数据)";
            logger.error(msg);
        }else {
            this.data=data;
            this.msg="请求成功";
            this.code=SUCCESS;
            logger.info(msg,data);
        }
    }
//    public Ret(String msg, String code, T data){
//        this(msg,code);
//        this.data=data;
//    }
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
  • 结果类使用
	@GetMapping(value = "/{id}")
    @Cacheable(value="user",key = "#id")
    @ApiOperation("根据用户唯一标识获取用户信息")
    public R getUser(@PathVariable @NonNull @ApiParam("用户唯一标识") String id)
    {
        return new R(iUserService.selectById(id));
    }
@PostMapping(value = "/")
    @CacheEvict(value = "user",key="'all'")
    @ApiOperation("添加用户")
    public R addUser(@RequestBody @ApiParam("用户信息") User user){
    	//...
	    if(iUserService.insert(user)){
	        return new R().success("注册成功",user);
        }
	    return new R().error("注册失败");
    }
  • 结果类的效果图

SpringBoot全局异常拦截处理类_Java