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分钟后再试!”}
小尾巴~~
只要有积累,就会有进步