一、单个controller范围的异常处理
/**
* 统一异常处理
* @return
*/
@RequestMapping("/exception")
public String exception(Date date) {
HelloModel helloModel = null;
helloModel.toString();
return "";
}
@ExceptionHandler(value = RuntimeException.class)
public Map exceptionHandller(){
Map handler = new HashMap();
handler.put("code","500");
handler.put("message","系统异常!");
return handler;
}说明:
- 在controller中加入被@ExceptionHandler修饰的方法即可(在该注解中指定该方法需要处理的那些异常类)
- 该异常处理方法只在当前的controller中起作用
二、全部controller范围内起作用的异常处理(全局异常处理)
1、全局异常处理类
package com.wxx.demo.handler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @Author : leisure
* @Date : 2019/1/23
*/
//@ControllerAdvice(annotations = RestController.class)//指定注解类
//@ControllerAdvice(basePackages = {"com.demo.xx","com.demo.xx"})//指定扫描包
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常捕捉处理
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 100);
map.put("msg", ex.getMessage());
return map;
}
}
说明:
- @ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
- @ControllerAdvice可以指定扫描范围
- @ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用@ResponseBody进行json转换
- 返回String,表示跳到某个view
- 返回modelAndView
- 返回model + @ResponseBody
注意:
- 同一个异常被局部范围异常处理器和全局范围异常处理器同时覆盖,会选择小范围的局部范围处理器
- 同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器