springBoot 全局异常捕捉
- 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 全局异常捕捉的更多相关文章
- springboot(四)拦截器和全局异常捕捉
github代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service 全部 ...
- android中全局异常捕捉
android中全局异常捕捉 只要写代码就会有bug,但是我们要想办法收集到客户的bug.有第三方bugly或者友盟等可以收集.但是,android原生就提供了有关收集异常的api,所以我们来学习一下 ...
- Spring 全局异常捕捉
Spring全局异常捕捉类 注解@ControllerAdvice package com.sicdt.sicsign.web.bill.controller; import org.springfr ...
- 在Spring Boot中添加全局异常捕捉提示
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...
- SpringBoot全局异常拦截
SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...
- 5.全局异常捕捉【从零开始学Spring Boot】
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...
- SpringBoot 全局异常配置
在日常web开发中发生了异常,往往是需要通过一个统一的异常处理来保证客户端能够收到友好的提示. 一.默认异常机制 默认异常处理(SpringBoot 默认提供了两种机制,一种是针对于web浏览器访问的 ...
- springboot 全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler
前言 本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用 ...
随机推荐
- Thinking-Bear magic (计算几何)
---- 点我 ---- 题目大意: 给你一个正n边形及边长 a和一个正整数L, 求正多边形的面积s,若s大于L,则连接相邻两边的中点,形成新的正多边形,重复这个操作直至s小于L:如图: 正多边形的面 ...
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...
- 把本地windows系统上的mysql数据库移到linux系统服务器上,mysql数据库拒绝访问
Mysql连接报错 原因是:远程服务器不允许你的其他程序访问它的数据库.所以,我们要对远程服务器进行设置,使它允许你进行连接. 步骤:一.进入mysql客户端,输入:use mysql; 二.输入:s ...
- ★★★kalinux 常用命令
1.修改密码: sudo passwd root 2.重启:reboot ====================================== arch 显示机器的处理器架构(1) una ...
- yum 原理C/S原理结构图
yum 原理C/S原理结构图
- 基于Kubernetess集群部署完整示例——Guestbook
目录贴:Kubernetes学习系列 本文依赖环境:Centos7部署Kubernetes集群.基于Kubernetes集群部署skyDNS服务 该示例中,我们将创建一个redis-master.两个 ...
- c# 使用checked和unchecked
首先要知道int型在c#中是一个32位的数.由此可以知道int型的取值范围是(-2147483648~2147483647)当要使用int的最小值或者是最大值的时候,可以使用int.MinValue和 ...
- 匿名内部类和内部类中的this
package test; public class A extends B { public String toString() { return "A"; } public s ...
- poj1185 [NOI2001炮兵阵地]
题目链接 状压DP 本来如果考虑所有情况应该开hh[n][2^10][2^10]表示i行在i-1的状态为j,i-2的状态为k的最大个数 但是由于每行中的人互相限制所以在m=10时只有60种情况 空间就 ...
- Python爬虫_Selenium与PhantomJS
Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动化操作,不同是Selenium可以直接运 ...