2024.10月12日--- SpringMVC异常处理

ops/2024/10/17 18:16:41/

异常处理

SpringMVC处理异常的方式有三种,当然也可以使用AOP面向编程,自定义一个类进入切入。

第一种:使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver

<!--SpringMVC提供的异常处理器类型:SimpleMappingExceptionResolver-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
   <!--  异常映射属性: 是一个map散列表 用于配置不同异常跳转到不同页面      -->
   <property name="exceptionMappings">
      <props>
         <!--key:  用于指定异常类型,  value用于指定跳转的页面名称-->
         <prop key="java.lang.Exception">error</prop>
      </props>
   </property>
</bean> 

第二种:实现HandlerExceptionResolver接口,自定义异常处理器,并注册

/**
 * 用户【】 IP[]
 * 在【时间】
 * 操作【Controller.find】 发生如下异常
 *   xxxxxxxxxxxxxxxxxxxxx
 *   yyyyyyyyyyyyyyyyyyyyy
 *
 */ 

package com.ssm.netctoss.util;

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

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

public class MyExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {

        ModelAndView modelAndView = new ModelAndView();
        System.out.println("---------执行了自定义异常处理器------------");
        // 根据不同的异常类型,设置不同的响应状态码
        if (e instanceof MyCustomException) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            // 可以添加更多的自定义处理逻辑
            System.out.println("-----");
        }else if (e instanceof IllegalArgumentException) {
            //
        }else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            // 记录日志或其他处理逻辑
        }
        // 可以将异常信息放入模型中供视图展示
        modelAndView.addObject("errorMessage", e.getMessage());

        // 设置视图名称
        modelAndView.setViewName("error");

        return modelAndView;
    }
}
class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}
 

xml配置文件添加: 

 <bean class="com.ssm.netctoss.util.MyExceptionResolver"/> 

 第三种:使用@ExceptionHandler注解实现异常处理

1. 编写如下方法
2. 在方法上添加注解
3. 其他Controller继承即可

package com.ssm.netctoss.util;

import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    @ExceptionHandler
    public String executeEx(HttpServletRequest request,Exception e){
//        request.setAttribute("msg", e.getMessage());
//        request.setAttribute("code", 1);
        System.out.println("---------------注解异常");
        //根据不同异常类型,返回不同视图
        return "error";
    }
}

第四种:使用AOP,自定义异常处理类型  

 可以正常统一处理异常信息 并且 开启注解扫描,别忘记了 

package com.ssm.netctoss;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ssm.netctoss.pojo.Admin;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;


/**
 * 用户【】 IP[]
 * 在【时间】
 * 操作【Controller.find】 发生如下异常
 *   xxxxxxxxxxxxxxxxxxxxx
 *   yyyyyyyyyyyyyyyyyyyyy
 *
 */
@Component
@Aspect
public class ExceptionLogger {
    @Resource
    private HttpServletRequest request;
    @Around("within(com.ssm.netctoss.controller..*)")
    public Object log(ProceedingJoinPoint p) throws Exception{
        Object obj = null;
        try {
            obj = p.proceed();
        } catch (Throwable e) {
            // 记录异常信息
            Admin admin = (Admin)request.getSession().getAttribute("LOGINADMIN");
            String msg="";
            if(admin!=null){
                String adminCode = admin.getAdminCode();
                String ip = request.getRemoteHost();
                String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                String className = p.getTarget().getClass().getName();
                String methodName = p.getSignature().getName();
                msg+="用户["+adminCode+"],IP["+ip+"],在"+now+"],操作["+className+"."+methodName+"]时,发生如下异常:\n";
            }
            StackTraceElement[] elems = e.getStackTrace();
            for(StackTraceElement elem:elems){
                msg+="\t"+elem.toString()+"\n";
            }
            Logger logger = Logger.getLogger(ExceptionLogger.class);
            logger.error(msg);
            //记录日志后,抛出异常,交给后面的代码继续处理
            throw new Exception(e);
        }
        return obj;
    }
}
 


http://www.ppmy.cn/ops/124784.html

相关文章

【排序算法】选择排序的全面剖析(含详细图解)

在之前文章中我们了解到了插入排序&#x1f449;【插入排序】&#xff0c;现在我们来学习排序算法中的直接选择排序。 目录 &#x1f4af;引言 &#x1f4af;选择排序的原理 &#x1f4af;选择排序的实现步骤 ⭐简单选择排序&#xff08;以升序为例&#xff09; ⭐代码实…

线性代数 矩阵

一、矩阵基础 1、定义 一组数按照矩形排列而成的数表&#xff1b;形似行列式&#xff0c;区别点是 矩阵行列式符号()或[]| |形状方阵或非方阵方阵本质数表数属性A|A|是A诸多属性中的一种维度m *n (m 与n可以相等也可以不相等)n*n 同型矩阵 若A、B两个矩阵都是mn 矩阵&#x…

享元模式(C++)

定义&#xff1a;享元模式是一种结构型设计模式&#xff0c;它使用共享对象&#xff0c;用以尽可能减少内存使用和提高性能。享元模式通过共享已经存在的对象实例&#xff0c;而不是每次需要时都创建新对象实例&#xff0c;从而避免大量重复对象的开销。 对比&#xff1a; 与单…

c语言链表实现

&#xff08;注意事项都已经在代码中标注&#xff09; 1.链表相关函数的头文件 #define _CRT_SECURE_NO_WARNINGS #pragma once #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <errno.h> #include <string.h> typede…

NVM 切换Node.js版本工具

大家好我是苏麟&#xff0c;今天聊聊NVM切换版本工具。 切换 node 版本工具 &#xff1a; GitHub - nvm-sh/nvm: Node Version Manager - POSIX-compliant bash script to manage multiple active node.js versions 查看node版本 node -v 查看 nvm 版本 nvm -v 查看可安装的Nod…

【Vue】Vue 快速教程

Vue tutorial 参考&#xff1a;教程 | Vue.js (vuejs.org) 该教程需要前置知识&#xff1a;HTML, CSS, JavaScript 学习前置知识&#xff0c;你可以去 MDN Vue framework 是一个 JavaScript framework&#xff0c;以下简称 Vue&#xff0c;下面是它的特点 声明式渲染&#xff…

Dify实现text2sql工作流[SQL调用篇],并查询Postgres数据库 or Mysql数据库(docker容器)

Dify 实现text2sql,查询Postgres数据库 1.Postgres数据库设置 1.1.docker-compose.yml修改 为了让 sandbox 容器能够与 docker-db-1 容器互相通信,你需要确保几个条件得到满足: 网络配置:确保 sandbox 和 db 都位于同一个 Docker 网络中。如果它们不在同一个网络中,数据…

《Spring Cloud 微服务:构建高效、灵活的分布式系统》

《Spring Cloud 微服务&#xff1a;构建高效、灵活的分布式系统》 一、引言 在当今快速发展的数字化时代&#xff0c;软件系统的规模和复杂性不断增加。为了应对这种挑战&#xff0c;微服务架构应运而生。Spring Cloud 作为构建微服务架构的强大工具集&#xff0c;提供了一系…