当前位置: 移动技术网 > IT编程>开发语言>Java > Spring boot 学习笔记 1 - 自定义错误

Spring boot 学习笔记 1 - 自定义错误

2018年10月08日  | 移动技术网IT编程  | 我要评论
spring boot提供了webexceptionhandler一个以合理的方式处理所有错误的方法。它在处理顺序中的位置就在webflux提供的处理程序之前,这被认为是最后一个处理程序。
对于机器客户端,它会生成一个json响应,其中包含错误,http状态和异常消息的详细信息。对于浏览器客户端,有一个“whitelabel”错误处理程序,它以html格式呈现相同的数据。您也可以提供自己的html模板来显示错误。
 
postman截图: 结果是json 格式
浏览器截图:
自定义errorpage的html:
在templates目录下添加 error页面,后缀根据模板引擎决定
 
定制此功能的第一步通常涉及使用现有机制,但替换或增加错误内容。为此,您可以添加一个类型的bean errorattributes。
要更改错误处理行为,可以实现errorwebexceptionhandler并注册该类型的bean定义。由于a webexceptionhandler的级别较低,因此spring boot还提供了一种方便的方式abstracterrorwebexceptionhandler,让您以webflux功能的方式处理错误,如以下示例所示:
public class customerrorwebexceptionhandler extends abstracterrorwebexceptionhandler {
// define constructor here
@override
protected routerfunction<serverresponse> getroutingfunction(errorattributes errorattributes) {
return routerfunctions
.route(apredicate, ahandler)
.androute(anotherpredicate, anotherhandler);
}
}
要获得更完整的图片,您还可以defaulterrorwebexceptionhandler 直接子类化并覆盖特定的方法。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网