SpringMVC_统一异常处理

用处:

我们只需在dao、service、controller层中向上抛出异常,则由DispatcherServlet接受到异常调用全局异常的处理方法进行处理

一、自定义异常处理类,继承Exception

package com.mingde.custom;

@SuppressWarnings("all")
public class CustomException extends Exception {
		private String message;
		
		public CustomException(String message) {
			this.message=message;
		}

		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		
}

二、实现全局异常处理功能(实现接口HandlerExceptionResolver)

package com.mingde.custom;

import java.io.IOException;

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

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

public class CustomExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception ex) {
		CustomException ce;
		//判断ex异常类型是否为CustomException,如果是就将其赋给CustomException对象,如果不是new一个未知异常
		if(ex instanceof CustomException){
			ce=(CustomException)ex;
		}else{
			ce=new CustomException("未知异常");
		}
		//将错误信息放入请求作用域中
		request.setAttribute("message", ce.getMessage());
		try {
			//进行页面的跳转,跳转到错误信息页面
			request.getRequestDispatcher("/WEB-INF/student/error.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
		return new ModelAndView();
	}

}

三、在SPringMVC.xml文件配置中配置上述该类、

<!-- 配置全局异常处理的javaBean,这样DispatcherServlet就可以直接访问他 -->
		<bean class="com.mingde.custom.CustomExceptionResolver"></bean>

方式二:也可以在CustomExceptionResolver类前面使用@Component 注解;前提是springmvc.xml文件配置中得有注解扫描器,并且能扫描到该类


示例:在控制层中向上抛出异常

假如“张三”是个敏感词语那么当在添加数据时则不允许用
if("张三".equals(st.getSname())){
			throw new CustomException("不能添加该名称");
		}

Spring MVC 中,我们可以通过实现一个异常处理器来统一处理控制器抛出的异常。具体步骤如下: 1. 实现一个异常处理器类,并添加 @ControllerAdvice 注解。 2. 在异常处理器类中定义处理不同类型异常的方法,并使用 @ExceptionHandler 注解标记。 3. 在方法中编写异常处理逻辑,例如将异常信息记录到日志中、返回错误信息等。 4. 如果需要返回 JSON 格式的错误信息,可以使用 @ResponseBody 注解。 以下是一个简单的示例: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> handleException(Exception e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "500"); errorMap.put("message", e.getMessage()); return errorMap; } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public Map<String, Object> handleValidationException(MethodArgumentNotValidException e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "400"); errorMap.put("message", "参数校验失败"); List<String> errors = e.getBindingResult() .getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList()); errorMap.put("errors", errors); return errorMap; } } ``` 在上述示例中,我们定义了两个处理异常的方法:handleException 和 handleValidationException。handleException 方法处理所有未被其他方法处理异常,返回一个包含错误码和错误信息的 Map 对象;handleValidationException 方法处理参数校验失败的异常,并将校验失败的所有错误信息返回。 最后,需要注意的是,如果同时存在多个异常处理方法,Spring MVC 会按照异常类型匹配最合适的处理方法。如果没有找到合适的处理方法,则会将异常抛给 Servlet 容器进行处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值