@ControllerAdvice
我们知道@ExceptionHandler注解可以注解到某个@Controller类的方法上,作为当前类的统一异常处理方法;如果我们想把这个异常处理方法作用于全局,那么就需要用到@ControllerAdvice注解,具体使用步骤如下:
@ControllerAdvice+@ExceptionHandler 实现全局异常配置
- 第一步自定义一个异常处理类,并标注 @ControllerAdice注解
- 第二步定义一个异常处理方法 并标注@ExceptionHandler
@ControllerAdvice
public class GlobleExceptionHandler {
/**
*功能描述
* @author qqg
* @date
* @param
* @return
*/
@ExceptionHandler(GlobleException.class)
public void uploadException(GlobleException ex, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.write("上传文件大小超出限制");
printWriter.flush();
printWriter.close();
}
/**
*功能描述
* @author qqg
* @date
* @param
* @return 方法可以有返回值,可以是一个json ,一个视图名等
*/
@ExceptionHandler(Exception.class)
public ModelAndView customException(Exception ex){
ModelAndView mv = new ModelAndView();
mv.addObject("mag","数据获取失败");
mv.setViewName("error");
return mv;
}
}
说明:
-
@ControllerAdvice注解
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @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 {}; }
// 指定作用在所有标注@RestController的类
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// 指定作用在指定的包的类
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// 指定在特殊的controller上
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
-
@ExceptionHandler注解
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExceptionHandler { Class<? extends Throwable>[] value() default {}; }@ExceptionHandler标注的方法支持以下参数:
方法参数 描述 异常类型 访问引发的异常 HandlerMethodFor access to the controller method that raised the exception. WebRequest,NativeWebRequestGeneric access to request parameters and request and session attributes without direct use of the Servlet API. javax.servlet.ServletRequest,javax.servlet.ServletResponseChoose any specific request or response type (for example, ServletRequestorHttpServletRequestor or Spring’sMultipartRequestorMultipartHttpServletRequest).javax.servlet.http.HttpSessionEnforces the presence of a session. As a consequence, such an argument is never null. Note that session access is not thread-safe. Consider setting theRequestMappingHandlerAdapterinstance’ssynchronizeOnSessionflag totrueif multiple requests are allowed to access a session concurrently.java.security.PrincipalCurrently authenticated user — possibly a specific Principalimplementation class if known.HttpMethodThe HTTP method of the request. java.util.LocaleThe current request locale, determined by the most specific LocaleResolveravailable — in effect, the configuredLocaleResolverorLocaleContextResolver.java.util.TimeZone,java.time.ZoneIdThe time zone associated with the current request, as determined by a LocaleContextResolver.java.io.OutputStream,java.io.WriterFor access to the raw response body, as exposed by the Servlet API. java.util.Map,org.springframework.ui.Model,org.springframework.ui.ModelMapFor access to the model for an error response. Always empty. RedirectAttributesSpecify attributes to use in case of a redirect — (that is to be appended to the query string) and flash attributes to be stored temporarily until the request after the redirect. See Redirect Attributes and Flash Attributes. @SessionAttributeFor access to any session attribute, in contrast to model attributes stored in the session as a result of a class-level @SessionAttributesdeclaration. See@SessionAttributefor more details.@RequestAttributeFor access to request attributes. See @RequestAttributefor more details.Return Values
@ExceptionHandlermethods support the following return values:Return value Description @ResponseBodyThe return value is converted through HttpMessageConverterinstances and written to the response. See@ResponseBody.HttpEntity,ResponseEntityThe return value specifies that the full response (including the HTTP headers and the body) be converted through HttpMessageConverterinstances and written to the response. See ResponseEntity.StringA view name to be resolved with ViewResolverimplementations and used together with the implicit model — determined through command objects and@ModelAttributemethods. The handler method can also programmatically enrich the model by declaring aModelargument (described earlier).ViewA Viewinstance to use for rendering together with the implicit model — determined through command objects and@ModelAttributemethods. The handler method may also programmatically enrich the model by declaring aModelargument (descried earlier).java.util.Map,org.springframework.ui.ModelAttributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator.@ModelAttributeAn attribute to be added to the model with the view name implicitly determined through a RequestToViewNameTranslator.Note that@ModelAttributeis optional. See “Any other return value” at the end of this table.ModelAndViewobjectThe view and model attributes to use and, optionally, a response status. voidA method with a voidreturn type (ornullreturn value) is considered to have fully handled the response if it also has aServletResponseanOutputStreamargument, or a@ResponseStatusannotation. The same is also true if the controller has made a positiveETagorlastModifiedtimestamp check (see Controllers for details).If none of the above is true, avoidreturn type can also indicate “no response body” for REST controllers or default view name selection for HTML controllers.Any other return value If a return value is not matched to any of the above and is not a simple type (as determined by BeanUtils#isSimpleProperty), by default, it is treated as a model attribute to be added to the model. If it is a simple type, it remains unresolved.
拦截器配置
-
自定义拦截器处理逻辑 实现HandlerInterceptor接口
public class CustormInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("拦截器处理逻辑......."); return true; } } -
注册拦截器类,实现WebMvcConfigurer
@Configuration public class InterceptorConfig implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CustormInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/index"); } }
错误页的配置
@ControllerAdvice定义的处理机制一般用来处理应用级别的异常,对于容器级别的错误还有另外一种形式;
springboot错误默认是由BasicErrorController类来处理的,该类源码:
static {
Map<Series, String> views = new EnumMap(Series.class);
views.put(Series.CLIENT_ERROR, "4xx");
views.put(Series.SERVER_ERROR, "5xx");
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}
如上可知:springboot默认会在error目录找4xx,5xx的文件作为错误视图,找不到会使用error视图作为错误页。
简单的建立如下目录:

本文介绍如何在SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常处理,包括自定义异常处理类、方法及参数,同时讲解了拦截器的配置与错误页的设置。

被折叠的 条评论
为什么被折叠?



