更新时间:2022-03-25 00:34:25
来自 Servlet Filter 的未到达控制器的异常由BasicErrorController
.
The exceptions from Servlet Filter which do not reach the controller are handled by
BasicErrorController
.
你需要重写BasicErrorController
来改变spring抛出的默认异常体.
You need to override the BasicErrorController
to change the default exception body thrown by spring.
如何覆盖:
@RestController
@Slf4j
public class BasicErrorControllerOverride extends AbstractErrorController {
public BasicErrorControllerOverride(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
/*
If you want to pull default error attributes and modify them, use this
Map<String, Object> defaultErrorAttributes = this.getErrorAttributes(request, false);
*/
Map<String, Object> errorCustomAttribute = new HashMap<>();
errorCustomAttribute.put("status", "error");
errorCustomAttribute.put("message", status.name());
return new ResponseEntity(errorCustomAttribute, status);
}
@Override
public String getErrorPath() {
return "/error";
}
}
错误响应的样子
{
"message": "UNAUTHORIZED",
"status": "error"
}