SpringMVC如何处理异常?

程序员考拉

共 3066字,需浏览 7分钟

 · 2020-09-11


一、描述


在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。 那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。 


二、Spring MVC处理异常常见方式


Spring MVC处理异常常见有两种方式: 


1、实现HandlerExceptionResolver 接口,自定义异常处理器;
2、使用注解@ExceptionHandler实现异常处理。

三、实战


1、实现HandlerExceptionResolver接口,自定义异常处理器。


package com.demo.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class MyHandlerExceptionResolver implements HandlerExceptionResolver{
    
    /**
     * 定义自己的异常处理器(实现HandlerExceptionResolver接口)
     *
     */

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex)
{
        
         ModelAndView mv=new ModelAndView();
         mv.addObject("ex",ex);
         mv.setViewName("error");
         return mv;

    }

}


然后在项目的配置文件中添加(spring-mvc.xml):



<bean class="com.demo.exception.MyHandlerExceptionResolver"/>


error.jsp


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
    <title>错误页面title>
    <link href="styles/main.css" />" type="text/css" rel="stylesheet" />
head>
<body style="margin:0 auto;text-align:center;">
    <div class="main" style="width:40%;">
        <h2 class="title"><span>出错啦!span>h2>
        <fieldset>
            <legend>错误信息legend>
            <p>
                ${ex.message}
            p
        fieldset>
    div>
body>
html>

  

这样就完成了异常的捕捉和处理。


2、使用注解@ExceptionHandler实现异常处理


我们介绍了第一种捕捉处理异常方式,但是第一种方式需要在配置文件中进行配置,有的时候我们会觉得配置文件内容太多太乱,那么我们就可以借助@ExceptionHandler注解来实现零配置的异常捕捉和处理。


首先,新建一个类,用于定义自己的异常处理器。注意,类中处理异常的方法要使用@ExceptionHandler注解。


package com.demo.exception;

import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;

public class MyHandlerExceptionResolver1 {
    
     @ExceptionHandler
     public String exception(HttpServletRequest request, Exception ex) {
              
         //添加自己的异常处理逻辑,如日志记录
         request.setAttribute("exceptionMessage", ex.getMessage());

         // 根据不同的异常类型进行不同处理
         if(ex instanceof SQLException){
             return "testerror";
         }else{
            return "error";
         }
      }

}


其次,新建一个HelloWorldController,让它继承于我们自己定义的注解异常处理器MyHandlerExceptionResolver1。


然后,修改HelloWorldController 中的index方法,使其抛出异常,看能不能正常捕捉。


package com.demo.controller;

import java.sql.SQLException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.demo.exception.MyHandlerExceptionResolver1;

@Controller
@RequestMapping("/hello")
public class HelloWorldController extends MyHandlerExceptionResolver1{
    
    @RequestMapping("/index")
    public ModelAndView index() throws SQLException{
        
        throw new SQLException("数据库异常!");
    }
}


最后,在views文件夹中添加testerror.jsp视图来显示错误信息:


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
    <title>错误页面title>
    <link href="styles/main.css" />" type="text/css" rel="stylesheet" />
head>
<body style="margin:0 auto;text-align:center;">
    <div class="main" style="width:40%;">
        <h2 class="title"><span>出错啦!span>h2>
        <fieldset>
            <legend>错误信息legend>
            <p>
                ${exceptionMessage}
            p
        fieldset>
    div>
body>
html>


运行项目:http://localhost/SSMProDemo/hello/index



可以看到异常已经被捕捉并显示,这样只要把我们的其它的Controller全部继承于BaseController就能实现异常的集中捕捉和处理了。



原文链接:cnblogs.com/xiaoxi/p/6273539.html





浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报