Spring MVC异常处理新策略

Spring MVC异常处理新策略

在Spring MVC框架中,异常处理是一个重要的话题。传统的异常处理方式可能无法满足我们对灵活性和定制化的需求。本文将展示如何通过自定义HandlerExceptionResolver接口的实现,来引入新的异常处理方式。

步骤概览

  1. 创建一个新的注解ErrorView,用于指定视图名称和状态码。
  2. 实现自定义的HandlerExceptionResolverHandlerExceptionToViewResolver,其resolveException()方法将检查异常发生处的方法是否有ErrorView注解。如果有,将获取注解中的视图名称和状态码,并设置响应的状态码后返回指定的错误页面。如果没有注解,则继续默认的错误处理。
  3. 创建控制器和JSP页面进行测试。

实现ErrorView注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) 
public @interface ErrorView {
    String value();
    HttpStatus status() default HttpStatus.INTERNAL_SERVER_ERROR;
}

自定义HandlerExceptionResolver

public class HandlerExceptionToViewResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                       HttpServletResponse response,
                                       Object handler,
                                       Exception ex) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            ErrorView errorView = hm.getMethodAnnotation(ErrorView.class);
            if (errorView != null) {
                String viewName = errorView.value();
                ModelAndView model = new ModelAndView(viewName);
                model.addObject("requestUri", request.getRequestURI());
                model.addObject("exception", ex);
                HttpStatus status = errorView.status();
                model.addObject("statusValue", status.value());
                model.addObject("statusStr", status.getReasonPhrase());
                response.setStatus(status.value());
                return model;
            }
        }
        return null;
    }
}

注册自定义HandlerExceptionResolver

@EnableWebMvc
@ComponentScan("com.logicbig.example") 
public class AppConfig {
    @Bean
    HandlerExceptionResolver customExceptionResolver() {
        return new HandlerExceptionToViewResolver();
    }
}

创建控制器

@Controller
public class ExampleController {
    @ErrorView(value = "test-error-view", status = HttpStatus.GONE)
    @RequestMapping("/test")
    public String handleRequest() throws Exception {
        throw new Exception("test exception");
    }
    @RequestMapping("/test2")
    public String handleRequest2() throws Exception {
        throw new OperationNotSupportedException("exception thrown in test2");
    }
    @ExceptionHandler
    public String handleException(OperationNotSupportedException e) {
        return "exception :" + e.toString();
    }
}

JSP错误页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<body>
    <h3>Test Error View</h3>
    <p>Request Uri: <b>${requestUri}</b></p>
    <p>Exception: <b>${exception['class'].name}</b></p>
    <p>Message: <b>${exception.message}</b></p>
    <p>Response status: <b>${statusValue} (${statusStr})</b></p>
</body>
</html>

运行内嵌Tomcat

使用Maven命令mvn tomcat7:run-war来启动应用。

输出示例

访问/test/test2路径,可以看到自定义异常处理的效果。

示例项目技术栈

  • Spring Web MVC 4.3.5.RELEASE
  • Java Servlet API 3.0.1
  • JDK 1.8
  • Maven 3.3.9

通过上述步骤,我们不仅能够自定义异常处理逻辑,还能在异常发生时提供更友好的用户提示,增强应用的健壮性和用户体验。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

t0_54coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值