@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
標註的方法支持以下參數:
方法參數 描述 異常類型 訪問引發的異常 HandlerMethod
For access to the controller method that raised the exception. WebRequest
,NativeWebRequest
Generic access to request parameters and request and session attributes without direct use of the Servlet API. javax.servlet.ServletRequest
,javax.servlet.ServletResponse
Choose any specific request or response type (for example, ServletRequest
orHttpServletRequest
or or Spring’sMultipartRequest
orMultipartHttpServletRequest
).javax.servlet.http.HttpSession
Enforces the presence of a session. As a consequence, such an argument is never null
. Note that session access is not thread-safe. Consider setting theRequestMappingHandlerAdapter
instance’ssynchronizeOnSession
flag totrue
if multiple requests are allowed to access a session concurrently.java.security.Principal
Currently authenticated user — possibly a specific Principal
implementation class if known.HttpMethod
The HTTP method of the request. java.util.Locale
The current request locale, determined by the most specific LocaleResolver
available — in effect, the configuredLocaleResolver
orLocaleContextResolver
.java.util.TimeZone
,java.time.ZoneId
The time zone associated with the current request, as determined by a LocaleContextResolver
.java.io.OutputStream
,java.io.Writer
For access to the raw response body, as exposed by the Servlet API. java.util.Map
,org.springframework.ui.Model
,org.springframework.ui.ModelMap
For access to the model for an error response. Always empty. RedirectAttributes
Specify 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. @SessionAttribute
For access to any session attribute, in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes
declaration. See@SessionAttribute
for more details.@RequestAttribute
For access to request attributes. See @RequestAttribute
for more details.Return Values
@ExceptionHandler
methods support the following return values:Return value Description @ResponseBody
The return value is converted through HttpMessageConverter
instances and written to the response. See@ResponseBody
.HttpEntity
,ResponseEntity
The return value specifies that the full response (including the HTTP headers and the body) be converted through HttpMessageConverter
instances and written to the response. See ResponseEntity.String
A view name to be resolved with ViewResolver
implementations and used together with the implicit model — determined through command objects and@ModelAttribute
methods. The handler method can also programmatically enrich the model by declaring aModel
argument (described earlier).View
A View
instance to use for rendering together with the implicit model — determined through command objects and@ModelAttribute
methods. The handler method may also programmatically enrich the model by declaring aModel
argument (descried earlier).java.util.Map
,org.springframework.ui.Model
Attributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator
.@ModelAttribute
An attribute to be added to the model with the view name implicitly determined through a RequestToViewNameTranslator
.Note that@ModelAttribute
is optional. See “Any other return value” at the end of this table.ModelAndView
objectThe view and model attributes to use and, optionally, a response status. void
A method with a void
return type (ornull
return value) is considered to have fully handled the response if it also has aServletResponse
anOutputStream
argument, or a@ResponseStatus
annotation. The same is also true if the controller has made a positiveETag
orlastModified
timestamp check (see Controllers for details).If none of the above is true, avoid
return 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視圖作爲錯誤頁。
簡單的建立如下目錄: