【发布时间】:2014-12-01 22:15:44
【问题描述】:
如果Spring Boot web应用发生异常,如何自定义响应状态码和响应体中的数据?
我创建了一个 Web 应用程序,如果由于某些不良的内部状态而发生意外情况,该应用程序会引发自定义异常。因此,触发错误的请求的响应正文如下所示:
HTTP/1.1 500 Internal Server Error
{
"timestamp": 1412685688268,
"status": 500,
"error": "Internal Server Error",
"exception": "com.example.CustomException",
"message": null,
"path": "/example"
}
现在,我想更改状态代码并设置响应正文中的字段。我想到的一个解决方案是:
@ControllerAdvice
class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ErrorMessage handleBadCredentials(CustomException e) {
return new ErrorMessage("Bad things happened");
}
}
@XmlRootElement
public class ErrorMessage(
private String error;
public ErrorMessage() {
}
public ErrorMessage(String error) {
this.error = error;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
)
但是,这产生了(怀疑)完全不同的反应:
HTTP/1.1 400 Bad Request
{
"error": "Bad things happened"
}
【问题讨论】:
-
@zeroflagL 最好,我想自定义 Spring Boot 生成的响应(如果可能的话)。实施一个完整的自定义解决方案(如问题中提供的解决方案)是可行的,但在不同项目之间的可重用性较差。
-
自定义解决方案是否可重用完全取决于您。 FWIW:resposne 主体由
DefaultErrorAttributes#getErrorAttributes组装。您可以将该类注入您的CustomResponseEntityExceptionHandler。
标签: java rest error-handling spring-boot