没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论























详解详解Spring Boot2 Webflux的全局异常处理的全局异常处理
主要介绍了详解Spring Boot2 Webflux的全局异常处理,小编觉得挺不错的,现在分享给大家,也给大家做个参
考。一起跟随小编过来看看吧
本文首先将会回顾Spring 5之前的SpringMVC异常处理机制,然后主要讲解Spring Boot 2 Webflux的全局异常处理机制。
SpringMVC的异常处理的异常处理
Spring 统一异常处理有 3 种方式,分别为:
使用 @ExceptionHandler 注解
实现 HandlerExceptionResolver 接口
使用 @controlleradvice 注解
使用使用 @ExceptionHandler 注解注解
用于局部方法捕获,与抛出异常的方法处于同一个Controller类:
@Controller
public class BuzController {
@ExceptionHandler({NullPointerException.class})
public String exception(NullPointerException e) {
System.out.println(e.getMessage());
e.printStackTrace();
return "null pointer exception";
}
@RequestMapping("test")
public void test() {
throw new NullPointerException("出错了!");
}
}
如上的代码实现,针对 BuzController 抛出的 NullPointerException 异常,将会捕获局部异常,返回指定的内容。
实现实现 HandlerExceptionResolver 接口接口
通过实现 HandlerExceptionResolver 接口,定义全局异常:
@Component
public class CustomMvcExceptionHandler implements HandlerExceptionResolver {
private ObjectMapper objectMapper;
public CustomMvcExceptionHandler() {
objectMapper = new ObjectMapper();
}
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object o, Exception ex) {
response.setStatus(200);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
Map<String, Object> map = new HashMap<>();
if (ex instanceof NullPointerException) {
map.put("code", ResponseCode.NP_EXCEPTION);
} else if (ex instanceof IndexOutOfBoundsException) {
map.put("code", ResponseCode.INDEX_OUT_OF_BOUNDS_EXCEPTION);
} else {
map.put("code", ResponseCode.CATCH_EXCEPTION);
}
try {
map.put("data", ex.getMessage());
response.getWriter().write(objectMapper.writeValueAsString(map));
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
资源评论


weixin_38614112
- 粉丝: 3
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 毕设&课设:开源合同管理系统,基于华炎魔方开发,多租户,云服务.zip
- 毕设&课设:酒店管理系统C#.zip
- 毕设&课设:外卖点餐系统--后台管理系统.zip
- 毕设&课设:班级管理系统.zip
- 毕设&课设:C语言期末大作业——图书信息管理系统(C语言,单链表).zip
- 毕设&课设:c#实现WinForm进销存系统.zip
- 毕设&课设:C#编写的图书馆管理系统,数据库使用SQL Server.zip
- 毕设&课设:基于STM32的智能门禁系统.zip
- 毕设&课设:C#桌面应用-仓库管理系统.zip
- 毕设&课设:强智教务系统验证码识别.zip
- 毕设&课设:C++小型图书馆管理系统(MFC).zip
- 毕设&课设:聊天系统后端.zip
- 毕设&课设:基于Tornado实现,系统核心调度,可分布式扩展.zip
- 毕设&课设:广告系统.zip
- 毕设&课设:使用 github actions 自动化编译 openwrt 系统。.zip
- 毕设&课设:C语言学生信息管理系统.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



安全验证
文档复制为VIP权益,开通VIP直接复制
