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";
	}

 

你可能感兴趣的:(Spring,MVC)