spring的@exceptionhandler和@controlleradvice统一处理异常

jxldjsn jxldjsn     2022-12-07     745

关键词:

之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch

try
..........
catch(Exception1 e)
..........
catch(Exception2 e)
...........
catch(Exception3 e)
...........


这样其实代码既不简洁好看 ,我们敲着也烦, 一般我们可能想到用拦截器去处理, 但是既然现在Spring这么火,AOP大家也不陌生, 那么Spring一定为我们想好了这个解决办法.果然: @ExceptionHandler

源码

//该注解作用对象为方法
@Target(ElementType.METHOD)
//在运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler
//value()可以指定异常类
Class<? extends Throwable>[] value() default ;


 @ControllerAdvice
源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
//bean对象交给spring管理生成
@Component
public @interface ControllerAdvice
@AliasFor("basePackages")
String[] value() default ;

@AliasFor("value")
String[] basePackages() default ;

Class<?>[] basePackageClasses() default ;

Class<?>[] assignableTypes() default ;

Class<? extends Annotation>[] annotations() default ;


从名字上可以看出大体意思是控制器增强

所以结合上面我们可以知道,使用@ExceptionHandler,可以处理异常, 但是仅限于当前Controller中处理异常, @ControllerAdvice可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.

 1.定义一个异常
public class CustomGenericException extends RuntimeException
private static final long serialVersionUID = 1L;

private String errCode;
private String errMsg;

public String getErrCode()
return errCode;

public void setErrCode(String errCode)
this.errCode = errCode;

public String getErrMsg()
return errMsg;

public void setErrMsg(String errMsg)
this.errMsg = errMsg;

public CustomGenericException(String errCode, String errMsg)
this.errCode = errCode;
this.errMsg = errMsg;



2. 定义一个controller
这里我们就不用try catch了, 直接抛异常就可以了

@Controller
@RequestMapping("/exception")
public class ExceptionController

@RequestMapping(value = "/type", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception
if ("error".equals(type))
// 由handleCustomException处理
throw new CustomGenericException("E888", "This is custom message");
else if ("io-error".equals(type))
// 由handleAllException处理
throw new IOException();
else
return new ModelAndView("index").addObject("msg", type);




3.异常处理类
这个类就可以当做controller类写了, 返回参数跟mvc返回参数一样

@ControllerAdvice
public class ExceptionsHandler

@ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public ModelAndView customGenericExceptionHnadler(CustomGenericException exception) //还可以声明接收其他任意参数
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errCode",exception.getErrCode());
modelAndView.addObject("errMsg",exception.getErrMsg());
return modelAndView;

//可以通过ResponseStatus配置返回的状态码
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
public ModelAndView allExceptionHandler(Exception exception)
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errMsg", "this is Exception.class");
return modelAndView;



4.jsp页面
正常的页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring MVC @ExceptionHandler Example</h2>

<c:if test="$not empty msg">
<h2>$msg</h2>
</c:if>

</body>
</html>

异常处理页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>

<c:if test="$not empty errCode">
<h1>$errCode : System Errors</h1>
</c:if>

<c:if test="$empty errCode">
<h1>System Errors</h1>
</c:if>

<c:if test="$not empty errMsg">
<h2>$errMsg</h2>
</c:if>

</body>
</html>

Spring ExceptionHandler 如何处理运行时异常

】SpringExceptionHandler如何处理运行时异常【英文标题】:HowRuntimeExceptionsarehandledbySpringExceptionHandler【发布时间】:2016-04-2707:32:37【问题描述】:我正在使用spring的@ControllerAdvice和@ExceptionHandler进行异常处理。任何方法都会从Controller... 查看详情

Spring @ExceptionHandler 不适用于 @ResponseBody

】Spring@ExceptionHandler不适用于@ResponseBody【英文标题】:Spring@ExceptionHandlerdoesnotworkwith@ResponseBody【发布时间】:2011-07-0302:23:11【问题描述】:我尝试为休息控制器配置一个弹簧异常处理程序,该处理程序能够根据传入的接受标头将... 查看详情

@ExceptionHandler 用于 Spring 中的包装异常 / getCause()

】@ExceptionHandler用于Spring中的包装异常/getCause()【英文标题】:@ExceptionHandlerforWrappedException/getCause()inSpring【发布时间】:2018-11-0423:22:22【问题描述】:有谁知道使用@ExceptionHandler包装异常的最佳/最简单方法?我有一个自定义org.spr... 查看详情

spring的@exceptionhandler注解无效问题

如果你想设置了@ExceptionHandler注解进行异常捕获返回异常信息,但是Debug调试时,代码并未进到被@ExceptionHandler注解标注的方法里,那么就检查你的配置文件是否包含 <mvc:annotation-driven/>注解,没有请添加上再尝试以下。&nb... 查看详情

spring新版本exceptionhandler了解

Spring注解ExceptionHandler,今天看新公司的项目发现的这个注解(以前公司用的版本低啊很多新特性都没有遇到过),用@RequestBody,@ResponseBody,可解决json绑定。但是每次遇到RuntimeException,需要给出一个默认返回JSON这一点比较繁琐... 查看详情

Spring Security - Ajax 调用忽略 @ExceptionHandler

】SpringSecurity-Ajax调用忽略@ExceptionHandler【英文标题】:SpringSecurity-Ajaxcallsignoring@ExceptionHandler【发布时间】:2016-08-1520:12:19【问题描述】:我的项目中有一个控制器来处理所有定义如下的异常:@ControllerAdvicepublicclassGlobalExceptionHand... 查看详情

@controlleradvice+@exceptionhandler全局处理controller层异常

@ControllerAdvice和@ExceptionHandler的区别ExceptionHandler,方法注解,作用于Controller级别.ExceptionHandler注解为一个Controler定义一个异常处理器.ControllerAdvice,类注解,作用于整个Spring工程.ControllerAdvice注解定义了一个全局的异常处理器.需要注意... 查看详情

如何在@ExceptionHandler(Spring REST)中获取@RequestBody

】如何在@ExceptionHandler(SpringREST)中获取@RequestBody【英文标题】:Howtogetthe@RequestBodyinan@ExceptionHandler(SpringREST)【发布时间】:2017-09-1601:45:01【问题描述】:我正在使用SpringBoot1.4.1,其中包括spring-web-4.3.3。我有一个用@ControllerAdvice... 查看详情

使用 Spring MVC Test 测试 Spring MVC @ExceptionHandler 方法

】使用SpringMVCTest测试SpringMVC@ExceptionHandler方法【英文标题】:TestingSpringMVC@ExceptionHandlermethodwithSpringMVCTest【发布时间】:2013-05-1604:22:03【问题描述】:我有以下简单的控制器来捕获任何意外异常:@ControllerAdvicepublicclassExceptionContro... 查看详情

来自客户端的 Spring Boot ExceptionHandler 捕获

】来自客户端的SpringBootExceptionHandler捕获【英文标题】:SpringbootExceptionHandlercatchfromClient【发布时间】:2017-12-3004:15:56【问题描述】:我开发了一个SpringBoot项目,我使用ExceptionHandler来捕获带有@RestControllerAdvice注释的所有异常。服... 查看详情

RestController 中 MethodArgumentNotValidException 的 Spring Boot ExceptionHandler 永远不会被调用

】RestController中MethodArgumentNotValidException的SpringBootExceptionHandler永远不会被调用【英文标题】:SpringBootExceptionHandlerforMethodArgumentNotValidExceptioninRestControllernevergetsinvoked【发布时间】:2021-05-2723:15:44【问题描述】:我正在使用Spr 查看详情

Tomcat中部署的Spring引导应用程序中的@ExceptionHandler没有返回@ResponseBody

】Tomcat中部署的Spring引导应用程序中的@ExceptionHandler没有返回@ResponseBody【英文标题】:No@ResponseBodyreturnedfrom@ExceptionHandlerinSpringbootappdeployedinTomcat【发布时间】:2015-05-1811:15:24【问题描述】:我有一个SpringBootWeb应用程序,它在STS... 查看详情

在启动 Spring Boot 应用程序时获取为 MethodArgumentNotValidException 映射的不明确的 @ExceptionHandler 方法

】在启动SpringBoot应用程序时获取为MethodArgumentNotValidException映射的不明确的@ExceptionHandler方法【英文标题】:GettingAmbiguous@ExceptionHandlermethodmappedforMethodArgumentNotValidExceptionwhilestartupofspringbootapplication【发布时间】:2019-01-3004: 查看详情

Spring @ControllerAdvice/@ExceptionHandler 不起作用

】Spring@ControllerAdvice/@ExceptionHandler不起作用【英文标题】:Spring@ControllerAdvice/@ExceptionHandlernotworking【发布时间】:2021-05-2209:36:45【问题描述】:我的SpringBoot服务将完成一项工作并在成功后以0退出(没有restcontroller),但我希望它... 查看详情

Spring boot @ExceptionHandler 将响应返回为 html

】Springboot@ExceptionHandler将响应返回为html【英文标题】:Springboot@ExceptionHandlerreturntheresponseashtml【发布时间】:2018-11-0707:03:58【问题描述】:我对Springboot更感兴趣当抛出异常时,我得到HTML的响应,而我需要它作为JSON。服务响应HTT... 查看详情

@ExceptionHandler 用于自定义 ResponseEntityExceptionHandler 中的 Spring 异常未调用类型异常

】@ExceptionHandler用于自定义ResponseEntityExceptionHandler中的Spring异常未调用类型异常【英文标题】:@ExceptionHandlerfortypeExceptionnotcalledforSpringexceptionincustomResponseEntityExceptionHandler【发布时间】:2017-03-2920:08:25【问题描述】:在阅读了一... 查看详情

如何确保 @ExceptionHandler(Exception.class) 在 Spring Boot 中最后被调用?

】如何确保@ExceptionHandler(Exception.class)在SpringBoot中最后被调用?【英文标题】:Howtomakesurethat@ExceptionHandler(Exception.class)willbecalledlastinSpringBoot?【发布时间】:2021-12-0822:07:42【问题描述】:我有一个控制器处理一些请求:@RequestMappin... 查看详情

@exceptionhandler注解和@controlleradvice注解(代码片段)

@ExceptionHandler注解和@ControllerAdvice注解上次学习自定义error页面,并没有真正的处理异常,在本此学习我们可以使用@ExceptionHandler注解处理异常,如果在Controller中有一个使用@ExceptionHandler注解修饰的方法࿰... 查看详情