(五)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] 内部错误,请联系管理员" }