SpringBoot项目处理filter中抛出的异常

SpringBoot项目处理filter中抛出的异常

0、备忘记录

1、在filter中抛出异常,会发现在统一异常处理里面接收不到filter中抛出的这个异常信息

2、filter中的异常走的是BasicErrorController,通过继承这个类可以定制化返回信息

3、代码如下

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @create 2020-05-22 18:01
 */
@RestController
public class ErrorController extends BasicErrorController {
    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> errorAttributes = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.EXCEPTION,ErrorAttributeOptions.Include.MESSAGE,ErrorAttributeOptions.Include.STACK_TRACE,ErrorAttributeOptions.Include.BINDING_ERRORS));
        HttpStatus status = getStatus(request);
        // 获取错误信息
        String code = errorAttributes.get("status").toString();
        String message = errorAttributes.get("message").toString();

        ApiErrorResult apiErrorResult = new ApiErrorResult(false,code,message);
        return new ResponseEntity<>(apiErrorResult,status);
    }
}

4、返回信息定义如下

import java.util.LinkedHashMap;

public class ApiErrorResult extends LinkedHashMap<String,Object> {
    private static final String SUCCESS_KEY = "success";
    private static final String CODE_KEY = "code";
    private static final String MESSAGE_KEY =  "message";

    public ApiErrorResult(boolean success, String code, String message) {
        this.put(SUCCESS_KEY,success);
        this.put(CODE_KEY,code);
        this.put(MESSAGE_KEY,message);
    }
}

5、返回信息如下
{“success”:false,“code”:“500”,“message”:“注册请求过于频繁,请10分钟后再试!”}

小尾巴~~
只要有积累,就会有进步

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值