除了使用注解,还有其他方式配置全局异常处理器吗?

除了使用注解的方式配置全局异常处理器外,还可以通过实现HandlerExceptionResolver接口来配置全局异常处理器。

以下是具体步骤:

一、创建自定义异常处理器类

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;

public class CustomExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        if (ex instanceof NullPointerException) {
            modelAndView.setViewName("error/null_pointer"); // 可以指向一个特定的错误页面视图名
            modelAndView.addObject("errorMessage", "发生了空指针异常:" + ex.getMessage());
        } else if (ex instanceof IllegalArgumentException) {
            modelAndView.setViewName("error/invalid_argument");
            modelAndView.addObject("errorMessage", "发生了非法参数异常:" + ex.getMessage());
        } else {
            modelAndView.setViewName("error/general");
            modelAndView.addObject("errorMessage", "发生了未知异常:" + ex.getMessage());
        }
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
}

二、注册自定义异常处理器

  1. 在 Spring Boot 的配置类中,可以通过以下方式注册自定义的异常处理器:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public HandlerExceptionResolver customExceptionResolver() {
        return new CustomExceptionHandler();
    }
}

通过这种方式,可以灵活地处理不同类型的异常,并可以根据需要返回特定的视图或 JSON 响应。同时,可以对异常进行更精细的处理和记录日志等操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值