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. SQl server更新某阶段的匹配关系。

    DECLARE @count INTEGERDECLARE @id INTEGERDECLARE @subjectID INTEGERSET @count=1SET @id =11894SET @su ...

  2. loadRunner回访脚本时报Error -27987: Requested image not found [MsgId: MERR-27987]

    loadRunner录制:登陆订机票网址->订机票的过程 loadRunner回访脚本时报Error -27987: Requested image not found  [MsgId: MER ...

  3. linux centos 如何设置swap大小?

    linux centos 如何设置swap大小? swap的值都是安装系统的时候设置好的,一般设置为内存的两倍大小.使用过程中发现swap值过小只能添加.用free -m 命令查看当前swap大小 使 ...

  4. js定时器优化

    在js中如果打算使用setInterval进行倒数,计时等功能,往往是不准确的,因为setInterval的回调函数并不是到时后立即执行,而是等系统计算资源空闲下来后才会执行.而下一次触发时间则是在s ...

  5. Mybatis+MySQL动态分页查询

    https://blog.csdn.net/qq_34137397/article/details/63289621 mybatis有两种分页方法 1.内存分页,也就是假分页.本质是查出所有的数据然后 ...

  6. Codeforce 835A - Key races

    Two boys decided to compete in text typing on the site "Key races". During the competition ...

  7. [转载]SQL中EXISTS的用法

    比如在Northwind数据库中有一个查询为SELECT c.CustomerId,CompanyName FROM Customers cWHERE EXISTS(SELECT OrderID FR ...

  8. 案例:通过shell脚本实现mysql数据备份与清理

    Shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口.它接收用户输入的命令并把它送入内核去执行,实际上Shell是一个命令解释器,它解释由用户输入的命令并且把它们送到内核,不仅如此,Sh ...

  9. github开源的一些ip解析 ,运营商信息,经纬度 地址 后续开发使用

    https://github.com/wzhe06/ipdatabase  ip解析 https://github.com/flyaction/ipdatabase 比较新 https://githu ...

  10. 【视频】使用fiddler开发工具进行新架构页面本地调试

    [视频]使用fiddler开发工具进行新架构页面本地调试,视频没录制好,有些部分比较模糊...