(五)SpringBoot如何定义全局异常
一:添加业务类异常
创建ServiceException
package com.example.demo.core.ret; import java.io.Serializable; /**
* @Description: 业务类异常
* @author
* @date 2018/4/20 14:30
*
*/
public class ServiceException extends RuntimeException implements Serializable{ private static final long serialVersionUID = 1213855733833039552L; public ServiceException() {
} public ServiceException(String message) {
super(message);
} public ServiceException(String message, Throwable cause) {
super(message, cause);
}
}
三:添加异常处理配置
在上篇讲过的创建的WebConfigurer.java类中,实现如下方法
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(getHandlerExceptionResolver());
} /**
* 创建异常处理
* @return
*/
private HandlerExceptionResolver getHandlerExceptionResolver(){
HandlerExceptionResolver handlerExceptionResolver = new HandlerExceptionResolver(){
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception e) {
RetResult<Object> result = getResuleByHeandleException(request, handler, e);
responseResult(response, result);
return new ModelAndView();
}
};
return handlerExceptionResolver;
} /**
* 根据异常类型确定返回数据
* @param request
* @param handler
* @param e
* @return
*/
private RetResult<Object> getResuleByHeandleException(HttpServletRequest request, Object handler, Exception e){
RetResult<Object> result = new RetResult<>();
if (e instanceof ServiceException) {
result.setCode(RetCode.FAIL).setMsg(e.getMessage()).setData(null);
return result;
}
if (e instanceof NoHandlerFoundException) {
result.setCode(RetCode.NOT_FOUND).setMsg("接口 [" + request.getRequestURI() + "] 不存在");
return result;
}
result.setCode(RetCode.INTERNAL_SERVER_ERROR).setMsg("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员");
String message;
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", request.getRequestURI(),
handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod() .getName(), e.getMessage());
} else {
message = e.getMessage();
}
LOGGER.error(message, e);
return result;
} /**
* @Title: responseResult
* @Description: 响应结果
* @param response
* @param result
* @Reutrn void
*/
private void responseResult(HttpServletResponse response, RetResult<Object> result) {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-type", "application/json;charset=UTF-8");
response.setStatus(200);
try {
response.getWriter().write(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue));
} catch (IOException ex) {
LOGGER.error(ex.getMessage());
}
}
四:添加配置文件
在 application.properties 中添加两个配置:
spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false
第一个spring.mvc.throw-exception-if-no-handler-found 告诉 SpringBoot 当出现 404 错误时, 直接抛出异常.
spring.resources.add-mappings 告诉 SpringBoot 不要为我们工程中的资源文件建立映射.五:创建测试接口
package com.example.demo.service.impl; import com.example.demo.core.ret.ServiceException;
import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.List; /**
* @author
* @Description:
* @time 2018/4/18 11:56
*/
@Service
public class UserInfoServiceImpl implements UserInfoService{ @Resource
private UserInfoMapper userInfoMapper; @Override
public UserInfo selectById(Integer id){
UserInfo userInfo = userInfoMapper.selectById(id);
if(userInfo == null){
throw new ServiceException("暂无该用户");
}
return userInfo;
}
}
结果
{
"code": 500,
"data": null,
"msg": "接口 [/userInfo/testException] 内部错误,请联系管理员"
}
(五)SpringBoot如何定义全局异常的更多相关文章
- 【快学springboot】5.全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- springboot编程之全局异常捕获
springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...
- 170621、springboot编程之全局异常捕获
1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.cla ...
- [四]SpringBoot 之 捕捉全局异常
在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下: package me.shi ...
- 从壹开始前后端分离 [.netCore 不定期更新 ] 三十五║ 完美实现全局异常日志记录
缘起 哈喽我是不定期更新的日常,昨天群里小伙伴问到了记录日志,当然,以前我也挖过这个坑,后来一直没有来得及填上,也想着 swagger 一直又有错误信息展示的功能,就迟迟没有添加这个功能,不过昨天夜里 ...
- springboot 全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- Springboot项目全局异常统一处理
转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...
- 【spring】-- springboot配置全局异常处理器
一.为什么要使用全局异常处理器? 什么是全局异常处理器? 就是把错误异常统一处理的方法. 应用场景: 1.当你使用jsr303参数校验器,如果参数校验不通过会抛异常,而且无法使用try-catch语句 ...
- SpringBoot 全局异常拦截捕获处理
一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...
随机推荐
- System V IPC相关函数
System V IPC 将一个已保存的路径名和一个整数标识符转换成一个key_t值,称为IPC键key_t:System V IPC(System V消息队列.System V信号量.System ...
- Centos6-编译安装Redis
[root@tbwy02 ~]# cd /tools/[root@tbwy02 tools]# yum install -y wget gcc make tcl[root@tbwy02 tools]# ...
- ubuntu git ssh不通
xyh@ubuntu-64:~$ ssh -v git@danxinben.com ...
- SSM整理笔记2——jar包整理
github:https://github.com/lakeslove/SSM 需要的jar包 springMVC和spring: spring.RELEASE.jar spring.RELEASE. ...
- numpy计算
import numpy as np import cv2 from PIL import Image #lenna.jpg # Create a black image #img=np.zeros( ...
- YARN commands are invoked by the bin/yarn script.
Apache Hadoop 2.9.0 – YARN Commands http://hadoop.apache.org/docs/stable/hadoop-yarn/hadoop-yarn-sit ...
- db_create_file_dest
<span><span>RAC中.将db_create_file_dest改动为本地路径,在创建表空间指定ASM磁盘组的时候还能够直接'+DATA'么?</span> ...
- mysql无法远程访问
最近使用Navicat for MySQl访问远程mysql数据库,出现报错, 显示“1130 - Host'xxx.xxx.xxx.xxx' is not allowed to connect to ...
- codeforces B. Shower Line 解题报告
题目链接:http://codeforces.com/contest/431/problem/B 题目意思:给出5 * 5 的矩阵.从这个矩阵中选出合理的安排次序,使得happiness之和最大.当第 ...
- BZOJ_4609_[Wf2016]Branch Assignment_决策单调性+带权二分
BZOJ_4609_[Wf2016]Branch Assignment_决策单调性+带权二分 Description 要完成一个由s个子项目组成的项目,给b(b>=s)个部门分配,从而把b个部门 ...