千家信息网

HandlerExceptionResolver中怎么实现全局异常捕获

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,本篇文章给大家分享的是有关HandlerExceptionResolver中怎么实现全局异常捕获,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看
千家信息网最后更新 2026年11月03日HandlerExceptionResolver中怎么实现全局异常捕获

本篇文章给大家分享的是有关HandlerExceptionResolver中怎么实现全局异常捕获,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

工程中我们不可否认的会出现异常,而且这些异常并没有进行捕获。经常出现的bug如空指针异常等等。在之前的项目中,如果我们没有进行任何配置,那么容器会自动打印错误的信息,如果tomcat的404页面,400页面等等。如果我们在web.xml中进行如下配置,就会拦截错误,然后跳转到指定的错误页面。

    500    /500.jsp

但是这已经落后了,现在我们通过实现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@Slf4jpublic class MyHandlerExceptionResolver implements HandlerExceptionResolver {    private ModelAndView modelAndView = new ModelAndView();    @Override    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {        try {            log.error("系统运行时异常:{}",e);            httpServletResponse.setCharacterEncoding("UTF-8");            httpServletResponse.setContentType("application/json");            httpServletResponse.getWriter().print(JSONObject.toJSON(ResultDTO.fail("系统异常")));        } catch (IOException e1) {            log.error("响应IO异常:{}",e1);        }        return modelAndView;    }}
import lombok.Data;@Datapublic class ResultDTO {    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  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  ResultDTO success(Integer code, String msg, T body){                return new ResultDTO(code,msg,body);        }}

以上就是HandlerExceptionResolver中怎么实现全局异常捕获,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

0