在SpringMVC重要注解@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。
package com.somnus.advice;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
@ResponseBody
public String handleArrayIndexOutOfBoundsException(Exception e) {
e.printStackTrace();
return "testArrayIndexOutOfBoundsException";
}
@Controller
@RequestMapping(value = "exception")
public class ExceptionHandlerController {
@RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
@ResponseBody
public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
List<String> list