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

异常处理

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;

}

}

相关推荐
咩咩啃树皮8 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
灯澜忆梦8 小时前
GO_并发编程---定时器
开发语言·后端·golang
鱟鲥鳚8 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
-银雾鸢尾-9 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-9 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司11 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地11 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415912 小时前
TCP超时重传机制是为了解决什么问题?
java
段一凡-华北理工大学12 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化