package cn.com.cs.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.Set; /**
* 异常处理类
*/
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class); /**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public String handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
logger.error("缺少请求参数", e);
return "缺少请求参数";
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public String handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("参数解析失败", e);
return "参数解析失败";
} /**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("参数验证失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return "参数验证失败="+message;
} /**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public String handleBindException(BindException e) {
logger.error("参数绑定失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return "参数绑定失败="+message;
} /**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public String handleServiceException(ConstraintViolationException e) {
logger.error("参数验证失败", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
return "参数验证失败" + message;
} /**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public String handleValidationException(ValidationException e) {
logger.error("参数验证失败", e);
return "参数验证失败";
} /**
* 404 - Not Found
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String noHandlerFoundException(NoHandlerFoundException e) {
logger.error("Not Found", e);
return "Not Found="+e;
} /**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public String handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("不支持当前请求方法", e);
return "request_method_not_supported";
} /**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
logger.error("不支持当前媒体类型", e);
return "content_type_not_supported";
}
/**
* 业务层需要自己声明异常的情况
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public String handleServiceException(ServiceException e) {
logger.error("业务逻辑异常", e);
return "业务逻辑异常:" + e.getMessage();
}
/**
* 操作数据或库出现异常
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(DataDoException.class)
public String handleException(DataDoException e) {
logger.error("操作数据库出现异常:", e);
return "操作数据库出现异常:字段重复、有外键关联等";
} /**
* 500 - Internal Server Error
*/
/* @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
logger.error("通用异常", e);
return "500通用异常:" + e.getMessage();
}*/ /**
* 获取其它异常。包括500
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public String defaultErrorHandler(Exception e){
logger.error("Exception", e); return "其它异常:" + e.getMessage(); } }

  

package cn.com.cs.core.exception;

/**
* 操作数据或库出现异常
*/
public class DataDoException extends RuntimeException{ public DataDoException(String msg) {
super(msg);
}
}

  

package cn.com.cs.core.exception;

/**
* 业务层需要自己声明异常的情况
*/
public class ServiceException extends RuntimeException{ public ServiceException(String msg) {
super(msg);
} }

  

#developEnvironment
spring:
mvc:
throw-exception-if-no-handler-found: true
resources:
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. Real Time Credit Card Fraud Detection with Apache Spark and Event Streaming

    https://mapr.com/blog/real-time-credit-card-fraud-detection-apache-spark-and-event-streaming/ Editor ...

  2. POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解

    http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280. ...

  3. E. Bear and Drawing

         E. Bear and Drawing time limit per test 1 second memory limit per test 256 megabytes input stan ...

  4. 【Linux学习一】命令查看与帮助

    环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 一.Linux执行命令流程:shell->bash(解释器 执行 ...

  5. window下安装cross-env解决NODE_ENV ts-node 不是内部或外部命令,也不是可运行的程序 或批处理文件 问题

    window下安装cross-env解决NODE_ENV ts-node 不是内部或外部命令,也不是可运行的程序 或批处理文件 问题 在git bash上启动无法进行调试,采用cross-env后可以 ...

  6. AtCoder Beginner Contest 045 C - たくさんの数式 / Many Formulas

    Time limit : 2sec / Memory limit : 256MB Score : 300 points Problem Statement You are given a string ...

  7. 洛谷 P1106 删数问题

    一定要认真审题   “去掉其中任意k个数字后剩下的数字按原左右次序将组成一个新的正整数”   也就是说 输入:7893400   4     输出:300  (00在原顺序中位于3后边) 输入:789 ...

  8. ubuntu数据库安装配置

    感谢原作者 http://www.linuxidc.com/Linux/2016-12/138081.htm

  9. myBatis框架之入门(一)

    什么是框架 框架就是一个架子,表演节目,舞台已经搭建好,表演什么节目,看自己的需求了. 框架是一个半成品,对于Java语言来说,框架就是封装了别人的代码.在框架的基础上我们在进一步开发,拿来主义. 框 ...

  10. shell 脚本的时间差计算

    在某个时间点上增加一段时间 将时间转为时间戳,然后增加时间 [root@~]# date +%s -d '2017-05-27 12:0:0' 1495857600 [root@ ~]# new_ti ...