Spring Boot中默認(rèn)帶了error的映射,但是這個(gè)錯(cuò)誤頁面顯示給用戶并不是很友好。
統(tǒng)一異常處理
通過使用@ControllerAdvice定義統(tǒng)一異常處理的類,而不是在每個(gè)Controller中逐個(gè)定義。
@ExceptionHandler用來定義函數(shù)針對(duì)的函數(shù)類型,最后將Exception對(duì)象和請(qǐng)求URL映射到URL中。
1
2
3
4
5
6
7
8
9
10
11
12
|
@ControllerAdvice class ExceptionTranslator { public static final String DEFAULT_ERROR_VIEW = "error" ; @ExceptionHandler (value = Exception. class ) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject( "exception" , e); mav.addObject( "url" , req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } } |
實(shí)現(xiàn)error.html頁面展示
在templates目錄下創(chuàng)建error.html。
例如:
1
2
3
4
5
6
7
8
9
10
11
12
|
<!DOCTYPE html> < html > < head lang = "en" > < meta charset = "UTF-8" /> < title >統(tǒng)一異常處理</ title > </ head > < body > < h1 >Error Handler</ h1 > < div th:text = "${url}" ></ div > < div th:text = "${exception.message}" ></ div > </ body > </ html > |
返回使用Json格式
只需在@ExceptionHandler之后加入@ResponseBody,就能讓處理函數(shù)return的內(nèi)容轉(zhuǎn)換為JSON格式
創(chuàng)建一個(gè)JSON返回對(duì)象,如:
1
2
3
4
5
6
7
|
public class ErrorDTO implements Serializable { private static final long serialVersionUID = 1L; private final String message; private final String description; private List<FieldErrorDTO> fieldErrors; //getter和setter省略 } |
可以為指定的Exception添加異常處理
1
2
3
4
5
6
|
@ExceptionHandler (ConcurrencyFailureException. class ) @ResponseStatus (HttpStatus.CONFLICT) @ResponseBody public ErrorDTO processConcurencyError(ConcurrencyFailureException ex) { return new ErrorDTO(ErrorConstants.ERR_CONCURRENCY_FAILURE); } |
ErrorConstants.ERR_CONCURRENCY_FAILURE 是定義的一個(gè)異常信息。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。