java – Spring Boot自定义http错误响应?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring Boot自定义http错误响应?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2218字,纯文字阅读大概需要4分钟。
内容图文
![java – Spring Boot自定义http错误响应?](/upload/InfoBanner/zyjiaocheng/700/ff37d9a5615d47ee8657313db5b592d7.jpg)
如果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在org.springframework.boot.autoconfigure.web.DefaultErrorAttributes中构建了“标准”错误响应体.与您的需求类似,我想利用所有这些,但只是增加了一些由我的一些例外提供的“类型”字段.
我通过实现对DefaultErrorAttributes进行子分类的Component来实现这一点. Spring Boot自动将其拾起并使用我的而不是默认值.
@Component
public class ExtendedErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
final Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
final Throwable error = super.getError(requestAttributes);
if (error instanceof TypeProvider) {
final TypeProvider typeProvider = (TypeProvider) error;
errorAttributes.put("type", typeProvider.getTypeIdentifier());
}
return errorAttributes;
}
}
有了这个,我得到了一个增强的JSON响应体,例如
{
"timestamp": 1488058582764,
"status": 429,
"error": "Too Many Requests",
"exception": "com.example.ExternalRateLimitException",
"message": "DAILY_LIMIT: too many requests",
"path": "/api/lookup",
"type": "DAILY_LIMIT"
}
内容总结
以上是互联网集市为您收集整理的java – Spring Boot自定义http错误响应?全部内容,希望文章能够帮你解决java – Spring Boot自定义http错误响应?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。