本篇文章給大家分享的是有關(guān)HandlerExceptionResolver中怎么實現(xiàn)全局異常捕獲,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

10年積累的成都做網(wǎng)站、成都網(wǎng)站制作經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先網(wǎng)站設計后付款的網(wǎng)站建設流程,更有余江免費網(wǎng)站建設讓你可以放心的選擇與我們合作。
工程中我們不可否認的會出現(xiàn)異常,而且這些異常并沒有進行捕獲。經(jīng)常出現(xiàn)的bug如空指針異常等等。在之前的項目中,如果我們沒有進行任何配置,那么容器會自動打印錯誤的信息,如果tomcat的404頁面,400頁面等等。如果我們在web.xml中進行如下配置,就會攔截錯誤,然后跳轉(zhuǎn)到指定的錯誤頁面。
<error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page>
但是這已經(jīng)落后了,現(xiàn)在我們通過實現(xiàn)spring的HandlerExceptionResolver接口來捕獲所有的異常。 主要作用是,比如當我們在Web API 提供服務的時候,API自己故障了,那么在API 故障前我們可以再設定一個springboot框架自身的 異常檢測。
demo如下:
package com.demo.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.credithc.kg.fetures.model.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
private ModelAndView modelAndView = new ModelAndView();
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
try {
log.error("系統(tǒng)運行時異常:{}",e);
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().print(JSONObject.toJSON(ResultDTO.fail("系統(tǒng)異常")));
} catch (IOException e1) {
log.error("響應IO異常:{}",e1);
}
return modelAndView;
}
}import lombok.Data;
@Data
public class ResultDTO<T> {
private Integer code;
private String msg;
private T body;
private ResultDTO(Integer code, String msg, T body) {
this.code = code;
this.msg = msg;
this.body = body;
}
public static <T> ResultDTO success(T body){
return success(200,"成功",body);
}
public static ResultDTO success(Integer code, String msg){
return success(code,msg,null);
}
public static ResultDTO fail(String msg){
return success(500,msg);
}
public static <T> ResultDTO success(Integer code, String msg, T body){
return new ResultDTO(code,msg,body);
}
}以上就是HandlerExceptionResolver中怎么實現(xiàn)全局異常捕獲,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當前文章:HandlerExceptionResolver中怎么實現(xiàn)全局異常捕獲
網(wǎng)頁路徑:http://chinadenli.net/article44/ggpoee.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設計公司、企業(yè)網(wǎng)站制作、網(wǎng)站營銷、靜態(tài)網(wǎng)站、營銷型網(wǎng)站建設、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)