一:添加业务类异常

创建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如何定义全局异常的更多相关文章

  1. 【快学springboot】5.全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  2. springboot编程之全局异常捕获

    springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...

  3. 170621、springboot编程之全局异常捕获

    1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.cla ...

  4. [四]SpringBoot 之 捕捉全局异常

    在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下: package me.shi ...

  5. 从壹开始前后端分离 [.netCore 不定期更新 ] 三十五║ 完美实现全局异常日志记录

    缘起 哈喽我是不定期更新的日常,昨天群里小伙伴问到了记录日志,当然,以前我也挖过这个坑,后来一直没有来得及填上,也想着 swagger 一直又有错误信息展示的功能,就迟迟没有添加这个功能,不过昨天夜里 ...

  6. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  7. Springboot项目全局异常统一处理

    转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...

  8. 【spring】-- springboot配置全局异常处理器

    一.为什么要使用全局异常处理器? 什么是全局异常处理器? 就是把错误异常统一处理的方法. 应用场景: 1.当你使用jsr303参数校验器,如果参数校验不通过会抛异常,而且无法使用try-catch语句 ...

  9. SpringBoot 全局异常拦截捕获处理

    一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...

随机推荐

  1. PHP中include路径修改

    1.__FILE__ __FILE__ always equals to the real path of a php script regardless whether it's included. ...

  2. Linux上Libevent的安装

    1.下载wget -O libevent-2.0.21-stable.tar.gz https://github.com/downloads/libevent/libevent/libevent-2. ...

  3. ssh命令、ping命令、traceroute 命令所使用的协议

    在Node reboot or eviction: How to check if yourprivate interconnect CRS can transmit network heartbea ...

  4. linux led子系统(一)

    就像学编程第一个范例helloworld一样,学嵌入式,单片机.fpga之类的第一个范例就是点亮一盏灯.对于庞大的linux系统,当然可以编写一个字符设备驱动来实现我们需要的led灯,也可以直接利用g ...

  5. php利用cookie防止重复提交解决办法

    原理:如果数据通过了上边的两次验证,说明数据是合法有效的数据,这时候我们把提交的数据串接为一个字符串,并用MD5加密后得到一个MD5的值. 接着我们把这个值通过Cookie放进客户端,当用户下一次提交 ...

  6. 值得收藏的45个Python优质资源(附链接)

    REST API:使用 Python,Flask,Flask-RESTful 和 Flask-SQLAlchemy 构建专业的 REST API https://www.udemy.com/rest- ...

  7. 浅谈JavaScript的事件(事件对象)

    在触发DOM上的某个事件时,会产生一个事件对象event,这个对象中包含这所有与事件有关的信息.包括导致事件的元素.事件的类型和事件的相关信息.例如鼠标操作的事件中,会包含鼠标的位置信息.而键盘触发的 ...

  8. 你的以太网速度足够快吗?四种更快的速度正在路上&#183;&#183;&#183;&#183;&#183;&#183;

    以太网的未来将远远超越下一个最快速度:为无处不在的网络协议绘制路径的网络project师们正在寻找新版本号来服务于各种应用程序. 在上周六的以太网联盟(一个行业组织,用于促进IEEE以太网标准)会议上 ...

  9. 浏览器上的Qt Quick

    你想不想在浏览器上运行你的Qt Quick程序呢?在Qt 5.12之前,唯一的方法是使用Qt WebGL Streaming技术把界面镜像到浏览器上.但该方法有不少缺陷,下文会说.前不久随着Qt 5. ...

  10. 微信公众号菜单与应用交互session

    http://www.cnblogs.com/yank/p/3476874.html http://blog.csdn.net/zmhawk/article/details/43671195 http ...