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分鐘後再試!”}

小尾巴~~
只要有積累,就會有進步

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章