1. package cn.com.cs.core.exception;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.converter.HttpMessageNotReadableException;
  7. import org.springframework.validation.BindException;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.validation.FieldError;
  10. import org.springframework.web.HttpMediaTypeNotSupportedException;
  11. import org.springframework.web.HttpRequestMethodNotSupportedException;
  12. import org.springframework.web.bind.MethodArgumentNotValidException;
  13. import org.springframework.web.bind.MissingServletRequestParameterException;
  14. import org.springframework.web.bind.annotation.ControllerAdvice;
  15. import org.springframework.web.bind.annotation.ExceptionHandler;
  16. import org.springframework.web.bind.annotation.ResponseBody;
  17. import org.springframework.web.bind.annotation.ResponseStatus;
  18. import org.springframework.web.servlet.NoHandlerFoundException;
  19.  
  20. import javax.validation.ConstraintViolation;
  21. import javax.validation.ConstraintViolationException;
  22. import javax.xml.bind.ValidationException;
  23. import java.util.Set;
  24.  
  25. /**
  26. * 异常处理类
  27. */
  28. @ControllerAdvice
  29. @ResponseBody
  30. public class CommonExceptionAdvice {
  31. private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);
  32.  
  33. /**
  34. * 400 - Bad Request
  35. */
  36. @ResponseStatus(HttpStatus.BAD_REQUEST)
  37. @ExceptionHandler(MissingServletRequestParameterException.class)
  38. public String handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
  39. logger.error("缺少请求参数", e);
  40. return "缺少请求参数";
  41. }
  42. /**
  43. * 400 - Bad Request
  44. */
  45. @ResponseStatus(HttpStatus.BAD_REQUEST)
  46. @ExceptionHandler(HttpMessageNotReadableException.class)
  47. public String handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
  48. logger.error("参数解析失败", e);
  49. return "参数解析失败";
  50. }
  51.  
  52. /**
  53. * 400 - Bad Request
  54. */
  55. @ResponseStatus(HttpStatus.BAD_REQUEST)
  56. @ExceptionHandler(MethodArgumentNotValidException.class)
  57. public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
  58. logger.error("参数验证失败", e);
  59. BindingResult result = e.getBindingResult();
  60. FieldError error = result.getFieldError();
  61. String field = error.getField();
  62. String code = error.getDefaultMessage();
  63. String message = String.format("%s:%s", field, code);
  64. return "参数验证失败="+message;
  65. }
  66.  
  67. /**
  68. * 400 - Bad Request
  69. */
  70. @ResponseStatus(HttpStatus.BAD_REQUEST)
  71. @ExceptionHandler(BindException.class)
  72. public String handleBindException(BindException e) {
  73. logger.error("参数绑定失败", e);
  74. BindingResult result = e.getBindingResult();
  75. FieldError error = result.getFieldError();
  76. String field = error.getField();
  77. String code = error.getDefaultMessage();
  78. String message = String.format("%s:%s", field, code);
  79. return "参数绑定失败="+message;
  80. }
  81.  
  82. /**
  83. * 400 - Bad Request
  84. */
  85. @ResponseStatus(HttpStatus.BAD_REQUEST)
  86. @ExceptionHandler(ConstraintViolationException.class)
  87. public String handleServiceException(ConstraintViolationException e) {
  88. logger.error("参数验证失败", e);
  89. Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
  90. ConstraintViolation<?> violation = violations.iterator().next();
  91. String message = violation.getMessage();
  92. return "参数验证失败" + message;
  93. }
  94.  
  95. /**
  96. * 400 - Bad Request
  97. */
  98. @ResponseStatus(HttpStatus.BAD_REQUEST)
  99. @ExceptionHandler(ValidationException.class)
  100. public String handleValidationException(ValidationException e) {
  101. logger.error("参数验证失败", e);
  102. return "参数验证失败";
  103. }
  104.  
  105. /**
  106. * 404 - Not Found
  107. */
  108. @ResponseStatus(HttpStatus.NOT_FOUND)
  109. @ExceptionHandler(NoHandlerFoundException.class)
  110. public String noHandlerFoundException(NoHandlerFoundException e) {
  111. logger.error("Not Found", e);
  112. return "Not Found="+e;
  113. }
  114.  
  115. /**
  116. * 405 - Method Not Allowed
  117. */
  118. @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
  119. @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  120. public String handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
  121. logger.error("不支持当前请求方法", e);
  122. return "request_method_not_supported";
  123. }
  124.  
  125. /**
  126. * 415 - Unsupported Media Type
  127. */
  128. @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
  129. @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
  130. public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
  131. logger.error("不支持当前媒体类型", e);
  132. return "content_type_not_supported";
  133. }
  134. /**
  135. * 业务层需要自己声明异常的情况
  136. */
  137. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  138. @ExceptionHandler(ServiceException.class)
  139. public String handleServiceException(ServiceException e) {
  140. logger.error("业务逻辑异常", e);
  141. return "业务逻辑异常:" + e.getMessage();
  142. }
  143. /**
  144. * 操作数据或库出现异常
  145. */
  146. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  147. @ExceptionHandler(DataDoException.class)
  148. public String handleException(DataDoException e) {
  149. logger.error("操作数据库出现异常:", e);
  150. return "操作数据库出现异常:字段重复、有外键关联等";
  151. }
  152.  
  153. /**
  154. * 500 - Internal Server Error
  155. */
  156. /* @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  157. @ExceptionHandler(Exception.class)
  158. public String handleException(Exception e) {
  159. logger.error("通用异常", e);
  160. return "500通用异常:" + e.getMessage();
  161. }*/
  162.  
  163. /**
  164. * 获取其它异常。包括500
  165. * @param e
  166. * @return
  167. * @throws Exception
  168. */
  169. @ExceptionHandler(value = Exception.class)
  170. public String defaultErrorHandler(Exception e){
  171. logger.error("Exception", e);
  172.  
  173. return "其它异常:" + e.getMessage();
  174.  
  175. }
  176.  
  177. }

  

  1. package cn.com.cs.core.exception;
  2.  
  3. /**
  4. * 操作数据或库出现异常
  5. */
  6. public class DataDoException extends RuntimeException{
  7.  
  8. public DataDoException(String msg) {
  9. super(msg);
  10. }
  11. }

  

  1. package cn.com.cs.core.exception;
  2.  
  3. /**
  4. * 业务层需要自己声明异常的情况
  5. */
  6. public class ServiceException extends RuntimeException{
  7.  
  8. public ServiceException(String msg) {
  9. super(msg);
  10. }
  11.  
  12. }

  

  1. #developEnvironment
  2. spring:
  3. mvc:
  4. throw-exception-if-no-handler-found: true
  5. resources:
  6. add-mappings: false

#出现错误时, 直接抛出异常

spring.mvc.throw-exception-if-no-handler-found=true

#不要为我们工程中的资源文件建立映射

spring.resources.add-mappings=false

************************

博主给自己的小程序打个广告,支付宝搜索: 天天购物助手

淘宝,天猫购物最高返利谢谢大家使用支持。

springBoot 全局异常捕捉的更多相关文章

  1. springboot(四)拦截器和全局异常捕捉

    github代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service 全部 ...

  2. android中全局异常捕捉

    android中全局异常捕捉 只要写代码就会有bug,但是我们要想办法收集到客户的bug.有第三方bugly或者友盟等可以收集.但是,android原生就提供了有关收集异常的api,所以我们来学习一下 ...

  3. Spring 全局异常捕捉

    Spring全局异常捕捉类 注解@ControllerAdvice package com.sicdt.sicsign.web.bill.controller; import org.springfr ...

  4. 在Spring Boot中添加全局异常捕捉提示

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...

  5. SpringBoot全局异常拦截

    SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...

  6. 5.全局异常捕捉【从零开始学Spring Boot】

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...

  7. SpringBoot 全局异常配置

    在日常web开发中发生了异常,往往是需要通过一个统一的异常处理来保证客户端能够收到友好的提示. 一.默认异常机制 默认异常处理(SpringBoot 默认提供了两种机制,一种是针对于web浏览器访问的 ...

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

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

  9. springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

    前言 本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用 ...

随机推荐

  1. Thinking-Bear magic (计算几何)

    ---- 点我 ---- 题目大意: 给你一个正n边形及边长 a和一个正整数L, 求正多边形的面积s,若s大于L,则连接相邻两边的中点,形成新的正多边形,重复这个操作直至s小于L:如图: 正多边形的面 ...

  2. mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...

  3. 把本地windows系统上的mysql数据库移到linux系统服务器上,mysql数据库拒绝访问

    Mysql连接报错 原因是:远程服务器不允许你的其他程序访问它的数据库.所以,我们要对远程服务器进行设置,使它允许你进行连接. 步骤:一.进入mysql客户端,输入:use mysql; 二.输入:s ...

  4. ★★★kalinux 常用命令

    1.修改密码: sudo  passwd  root 2.重启:reboot ====================================== arch 显示机器的处理器架构(1) una ...

  5. yum 原理C/S原理结构图

    yum 原理C/S原理结构图

  6. 基于Kubernetess集群部署完整示例——Guestbook

    目录贴:Kubernetes学习系列 本文依赖环境:Centos7部署Kubernetes集群.基于Kubernetes集群部署skyDNS服务 该示例中,我们将创建一个redis-master.两个 ...

  7. c# 使用checked和unchecked

    首先要知道int型在c#中是一个32位的数.由此可以知道int型的取值范围是(-2147483648~2147483647)当要使用int的最小值或者是最大值的时候,可以使用int.MinValue和 ...

  8. 匿名内部类和内部类中的this

    package test; public class A extends B { public String toString() { return "A"; } public s ...

  9. poj1185 [NOI2001炮兵阵地]

    题目链接 状压DP 本来如果考虑所有情况应该开hh[n][2^10][2^10]表示i行在i-1的状态为j,i-2的状态为k的最大个数 但是由于每行中的人互相限制所以在m=10时只有60种情况 空间就 ...

  10. Python爬虫_Selenium与PhantomJS

    Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动化操作,不同是Selenium可以直接运 ...