SpringBoot自定義錯誤信息,SpringBoot適配Ajax請求


SpringBoot自定義錯誤信息,SpringBoot自定義異常處理類,

SpringBoot異常結果處理適配頁面及Ajax請求,

SpringBoot適配Ajax請求

 

================================

©Copyright 蕃薯耀 2018年3月29日

http://www.cnblogs.com/fanshuyao/

 

附件&源碼下載見:http://fanshuyao.iteye.com/blog/2414865

 

一、自定義異常處理類:

Java代碼   收藏代碼
  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3.   
  4. import javax.servlet.http.HttpServletRequest;  
  5.   
  6. import org.springframework.web.bind.annotation.ControllerAdvice;  
  7. import org.springframework.web.bind.annotation.ExceptionHandler;  
  8.   
  9. import com.lqy.springboot.component.CustomErrorAttribute;  
  10.   
  11. @ControllerAdvice  
  12. public class CustomExceptionHandler {  
  13.       
  14.     /** 
  15.      * 自定義異常數據 
  16.      * 缺點,沒有適配頁面和Ajax請求,返回的數據都是json數據 
  17.      * @param req 
  18.      * @return 
  19.      */  
  20.     /*@ResponseBody 
  21.     @ExceptionHandler(Exception.class) 
  22.     public Map<String, Object> exceptionHandler(HttpServletRequest req){ 
  23.         Map<String, Object> map = new HashMap<String, Object>(); 
  24.         map.put("errorCode", 500); 
  25.         map.put("errorMsg", "錯誤信息"); 
  26.         map.put("errorSystem", "errorSystem"); 
  27.         return map; 
  28.     }*/  
  29.       
  30.     /** 
  31.      * 自定義異常數據 
  32.      * 適配頁面和Ajax請求 
  33.      * 注解ExceptionHandler(Exception.class)的Exception.class可以替換成自己定義的錯誤異常類 
  34.      * @param req 
  35.      * @return 
  36.      */  
  37.     @ExceptionHandler(Exception.class)  
  38.     public String exceptionHandler(HttpServletRequest req){  
  39.         Map<String, Object> map = new HashMap<String, Object>();  
  40.         map.put("errorCode", 500);  
  41.         map.put("errorMsg", "錯誤信息");  
  42.         map.put("errorSystem", "errorSystem");  
  43.         req.setAttribute(CustomErrorAttribute.CUSTOM_ERROR_MAP_NAME, map);  
  44.           
  45.         //傳入自己的錯誤代碼,必須的,否則不會進入自定義錯誤頁面,見:org.springframework.boot.autoconfigure.web.AbstractErrorController  
  46.         req.setAttribute("javax.servlet.error.status_code", 500);  
  47.           
  48.         //轉發到springBoot錯誤處理請求,能適配網頁和Ajax的錯誤處理  
  49.         //請求/error后,會進入BasicErrorController(@RequestMapping("${server.error.path:${error.path:/error}}"))  
  50.         //頁面的數據顯示處理是使用:errorAttributes.getErrorAttributes獲取顯示的,是AbstractErrorController的方法  
  51.         //當需要把自己定義的Map錯誤信息傳遞到錯誤提示頁面時,  
  52.         //可以編寫一個自定義錯誤屬性類處理:CustomErrorAttribute,繼承DefaultErrorAttributes類,  
  53.         //重寫getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace)方法  
  54.         return "forward:/error";  
  55.     }  
  56.       
  57. }  

 

異常捕捉后請求轉發到

Java代碼   收藏代碼
  1. return "forward:/error";  

 是為了讓SpringBoot底層處理,協助系統適配頁面返回結果和Ajax返回結果:當是頁面打開時,會跳轉到相應的錯誤頁面顯示異常信息,當是Ajax請求或者使用工具請求時,返回的json字符串。(下面有圖)

 

SpringBoot適配頁面返回結果和Ajax返回結果的代碼如下:

Java代碼   收藏代碼
  1. @RequestMapping(produces = "text/html")  
  2.     public ModelAndView errorHtml(HttpServletRequest request,  
  3.             HttpServletResponse response) {  
  4.         HttpStatus status = getStatus(request);  
  5.         Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(  
  6.                 request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));  
  7.         response.setStatus(status.value());  
  8.         ModelAndView modelAndView = resolveErrorView(request, response, status, model);  
  9.         return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);  
  10.     }  
  11.   
  12.     @RequestMapping  
  13.     @ResponseBody  
  14.     public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {  
  15.         Map<String, Object> body = getErrorAttributes(request,  
  16.                 isIncludeStackTrace(request, MediaType.ALL));  
  17.         HttpStatus status = getStatus(request);  
  18.         return new ResponseEntity<Map<String, Object>>(body, status);  
  19.     }  

 

 

二、自定義異常信息傳遞類

Java代碼   收藏代碼
  1. import java.util.Map;  
  2.   
  3. import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;  
  4. import org.springframework.stereotype.Component;  
  5. import org.springframework.web.context.request.RequestAttributes;  
  6.   
  7. @Component  
  8. public class CustomErrorAttribute extends DefaultErrorAttributes {  
  9.       
  10.     public static final String CUSTOM_ERROR_MAP_NAME = "customErrorMap";  
  11.   
  12.     @Override  
  13.     public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {  
  14.         Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);  
  15.           
  16.         //設置傳遞自己定義的錯誤信息  
  17.         map.put(CUSTOM_ERROR_MAP_NAME, requestAttributes.getAttribute(CUSTOM_ERROR_MAP_NAME, RequestAttributes.SCOPE_REQUEST));  
  18.         return map;  
  19.     }  
  20.       
  21. }  

定義這個類,是為了傳遞自己想要顯示的錯誤信息,例如在Controller發生錯誤時,想把某些特殊信息傳到錯誤頁面,就可以自定義一個異常信息處理類,傳遞自己的自定義錯誤信息,同時也兼容SpringBoot本身定義好的錯誤 信息。

 

三、頁面顯示異常信息

Html代碼   收藏代碼
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>500</title>  
  6. </head>  
  7. <body>  
  8.     <div>500錯誤</div>  
  9.     <div>path:[[${path}]]</div>  
  10.     <div>status:[[${status}]]</div>  
  11.     <div>timestamp:[[${#dates.format(timestamp, 'yyyy-MM-dd HH:mm:ss')}]]</div>  
  12.     <div>error:[[${error}]]</div>  
  13.     <div>exception:[[${exception}]]</div>  
  14.     <div>message:[[${message}]]</div>  
  15.     <div>errors:[[${errors}]]</div>  
  16.     <!-- 自定義屬性 -->  
  17.     <div>customErrorMap.errorMsg:[[${customErrorMap.errorMsg}]]</div>  
  18.     <div>customErrorMap.errorSystem:[[${customErrorMap.errorSystem}]]</div>  
  19.     <div>customErrorMap.errorCode:[[${customErrorMap.errorCode}]]</div>  
  20. </body>  
  21. </html>  

 

頁面顯示結果:


 

Post請求結果:


 

項目源碼見附件:SpringBoot-自定義錯誤.zip

 

 

======SpringBoot自定義錯誤頁面見:======

SpringBoot自定義錯誤頁面,SpringBoot 404、500錯誤提示頁面

SpringBoot 4xx.html、5xx.html錯誤提示頁面

http://www.cnblogs.com/fanshuyao/p/8668072.html

 

 

(如果你覺得文章對你有幫助,歡迎捐贈,^_^,謝謝!) 

 

 

 

================================

©Copyright 蕃薯耀 2018年3月29日

http://www.cnblogs.com/fanshuyao/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM