springboot中抛出异常,springboot自带的是springmvc框架,这个就不多说了。

springmvc统一异常解决方法这里要说明的是。只是结合了springboot的使用而已。直接上代码,有效有用的才是ok。

1.定义异常捕获

package com.example.rest.error;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolationException; /**
*
* @author ming 定义全局异常处理
* @RestControllerAdvice 是@controlleradvice 与@ResponseBody 的组合注解
*/
@RestControllerAdvice
public class GlobalControllerExceptionHandler { @ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse constraintViolationException(ConstraintViolationException ex) {
return new ApiErrorResponse(500, 5001, ex.getMessage());
} @ExceptionHandler(value = { IllegalArgumentException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiErrorResponse IllegalArgumentException(IllegalArgumentException ex) {
return new ApiErrorResponse(501, 5002, ex.getMessage());
} @ExceptionHandler(value = { NoHandlerFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiErrorResponse noHandlerFoundException(Exception ex) {
return new ApiErrorResponse(404, 4041, ex.getMessage());
} @ExceptionHandler(value = { Exception.class })
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiErrorResponse unknownException(Exception ex) {
return new ApiErrorResponse(500, 5002, ex.getMessage());
}
}

2.定义一个返回对象

package com.example.rest.error;

/**
* @author ming
*/
public class ApiErrorResponse { private int status;
private int code;
private String message; public ApiErrorResponse(int status, int code, String message) {
this.status = status;
this.code = code;
this.message = message;
} public int getStatus() {
return status;
} public int getCode() {
return code;
} public String getMessage() {
return message;
} @Override
public String toString() {
return "ApiErrorResponse{" +
"status=" + status +
", code=" + code +
", message=" + message +
'}';
}
}

3.定义一个启动Application

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; @SpringBootApplication
@EnableWebMvc
public class SpringBootExceptionHandlingApplication { public static void main(String[] args) {
SpringApplication.run(SpringBootExceptionHandlingApplication.class, args);
}
}

4.最后一个测试类

package com.example.rest.controller;

import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import javax.validation.ConstraintViolationException;
import java.util.Collections; /**
* @author ming
*/
@RestController
public class TestController { @GetMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public void test(Long id) {
Assert.notNull(id,"id不能为空!");
throw new ConstraintViolationException("error", Collections.emptySet());
}
}

注意application.properties这个文件的配置

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

ok,springboot中解决springmvc异常抛出就可以这样解决了。

springboot springmvc 抛出全局异常解决方法的更多相关文章

  1. 在命令行运行 python 抛出 ModuleNotFoundError 的解决方法

    所要运行的 py 文件在子目录中,并且该文件引用了另一个子目录中的 py 模块.类似这样: 原因 在运行环境下, a.py 找不到 b.py 所以抛出 ModuleNotFoundError. 解决 ...

  2. Android 异常解决方法【汇总】

    (1)异常:Android中引入第三方Jar包的方法(Java.lang.NoClassDefFoundError解决办法) 1.在工程下新建lib文件夹,将需要的第三方包拷贝进来.2.将引用的第三方 ...

  3. 在SpringMVC中,当Json序列化,反序列化失败的时候,会抛出HttpMessageNotReadableException异常, 当Bean validation失败的时候,会抛出MethodArgumentNotValidException异常,因此,只需要在ExceptionHandler类中添加处理对应异常的方法即可。

    在SpringMVC中,当Json序列化,反序列化失败的时候,会抛出HttpMessageNotReadableException异常, 当Bean validation失败的时候,会抛出Method ...

  4. 外部无法捕捉Realm的doGetAuthenticationInfo方法抛出的异常

    shiro权限框架,用户登录方法的subject.login(token)会进入自定义的UserNamePasswordRealm类的doGetAuthenticationInfo身份验证方法 通常情 ...

  5. springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。

    springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑. 1.1 异常处理思路 系统中异常包括两类:预期异常和运行时异常RuntimeEx ...

  6. 解决httpclient抛出URISyntaxException异常

    这两天在使用httpclient发送http请求的时候,发现url中一旦包含某些特殊字符就会报错.抛出URISyntaxException异常,比如struts漏洞的利用url:(大括号就不行) re ...

  7. “全栈2019”Java异常第十一章:重写方法时只能抛出父类异常子集

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...

  8. JUnit 判断方法抛出的异常

    :比方案1更详细,可以进一步判断抛出的异常的报错信息是否符合预期 不用上面那个属性,用 try - catch(因为判断了报错信息,所以不用判断异常的类型了吧) ( 注释:MyAssert类是我自定义 ...

  9. Spring-MVC开发之全局异常捕获全面解读

    异常,异常 我们一定要捕获一切该死的异常,宁可错杀一千也不能放过一个! 产品上线后的异常更要命,一定要屏蔽错误内容,以免暴露敏感信息! 在用Spring MVC开发WEB应用时捕获全局异常的方法基本有 ...

随机推荐

  1. 注意!!一定要谨慎使用c/c++原生指针

    使用指针,要非常小心,今天在做一个小游戏时,就碰到一个使用原生指针的问题,找了好几个小时,才定位到问题的所在,晕. 主要是顶层逻辑中引用了一个指针,而在业务逻辑中将此指针删除了.这种在代码量很少的情况 ...

  2. <<Senium2自动化测试>>读书笔记二

    为进一步加强Python知识扩展和学习,在朋友的推荐下选择了<<Selenium2自动化测试实战>>,作者胡志恒,基于Python语言实现,以实例的方式详细讲解WebDrive ...

  3. POJ2387(最短路入门)

    Til the Cows Come Home Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 38556   Accepted ...

  4. NSCLIENT++可以采集的指标

    Documentation   Information   Commands/Modules   CheckDisk   CheckFileSize   CheckDriveSize   CheckF ...

  5. cocos2dx 3.0 用ClippingNode做游戏的新手引导

    转自:http://blog.csdn.net/star530/article/details/20851263 本篇介绍的是用ClippingNode 做游戏的新手引导,额,或者说是做新手引导的一种 ...

  6. Linux命令总结_命令执行顺序

    有时候,我们需要一个命令执行完之后再去执行另一个命令,使用 &&和 ||可以完成 这样的功能,相应的命令可以是系统命令或shell脚本 Shell还提供了在当前shell或子shell ...

  7. K-S Test

    K-S test, test for the equality of continuous, one-dimensional probability distribution that can be ...

  8. openstack介绍(二)

    OpenStack services 本节将详细描述OpenStack服务. Compute service overview(计算服务概述) 使用OpenStack云计算计算主机和管理系统.Open ...

  9. iis部署错误:HTTP 错误 500.21 - Internal Server Error

    将网站发布到IIS,访问发生如下错误: HTTP 错误 500.21 - Internal Server Error处理程序“PageHandlerFactory-Integr”在其模块列表中有一个错 ...

  10. IE11浏览器中的My97日历控件刷新后无法打开问题解决办法

    IE11浏览器中的My97日历控件刷新后无法打开问题解决办法   IE11浏览器中的My97日历控件刷新后无法打开问题解决办法:(谷歌浏览器下正常.IE11失效) 解决办法:1:找到WdatePick ...