springmvc三十:异常处理流程

handlerExceptionResolvers 异常解析也是springmvc的9大组件之一。

 

DispatcherServlet.properties中默认的异常解析如下:

org.springframework.web.servlet.HandlerExceptionResolver=

    org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver 处理@ExceptionHandler
    org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver 处理@ResponseStatus, @ResponseStatus标注在自定义异常类上
    org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 判断是否SpringMVC自带的异常

 

package com.atchina;

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

@Controller
public class ExceptionTestController {

	@RequestMapping("/handler01")
	public String handler01(Integer i){
		System.out.println(10/i);
		return "success";
	}
	
	/**
	 * 告诉SpringMVC这个方法专门处理这个类发生的异常 
	 * 1. 给方法写一个Exception,接受发生的异常
	 * 2. 返回ModelAndView
	 */
	@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})
	public ModelAndView handleException01(Exception exception){
		
		ModelAndView andView = new ModelAndView("myerror");
		andView.addObject("ex", exception);
		return andView;
	}
}

  全局异常处理类

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

// 集中处理所有异常的类加入到ioc容器中
// @ControllerAdvice专门处理异常的类
@ControllerAdvice
public class MyGlobalException {
	
	@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})
	public ModelAndView handleException01(Exception exception){
		
		ModelAndView andView = new ModelAndView("myerror");
		andView.addObject("ex", exception);
		return andView;
	}
}

 使用HttpStatus

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(reason="用户名不正确", code=HttpStatus.NOT_ACCEPTABLE)
public class UserNameNotFoundException extends RuntimeException{

	private static final long serialVersionUID = 1L;

}

  测试

@RequestMapping("/handler02")
	public String handler02(@RequestParam("username")String username){
		if(!"admin".equals(username)){
			throw new UserNameNotFoundException();
		}
		return "success";
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值