继上一篇博客《Spring学习(八)——Spring MVC之Restful API返回json数据》之后,还有一个点需要注意一下,就是Spring MVC的全局异常处理,当然,这个异常处理其实就是个异常通知(advice),当发生异常时,就会进入该模块。
一、原Controller模拟抛异常
接着上次的代码写,原来的Controller代码长这个样:
package cool.gjh.controller;
import cool.gjh.entity.Student;
import cool.gjh.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Controller层
* <p>
* Restful风格,返回json数据
* </p>
* @author ACE_GJH
*/
@Controller
@RequestMapping("/student")
public class StudentRestfulController {
@Autowired
private StudentService studentService;
@ResponseBody
@RequestMapping(value = "/data", method = RequestMethod.GET)
public Map<String, Object> showAll(){
List<Student> students = studentService.getAllStudent();
HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f);
data.put("code", 200);
data.put("msg", "OK");
data.put("data", students);
data.put("date", System.currentTimeMillis());
return data;
}
}
现在抛出个异常:
@ResponseBody
@RequestMapping(value = "/data", method = RequestMethod.GET)
public Map<String, Object> showAll(){
List<Student> students = studentService.getAllStudent();
HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f);
data.put("code", 200);
data.put("msg", "OK");
data.put("data", students);
data.put("date", System.currentTimeMillis());
throw new RuntimeException("服务器出现异常");
}
二、创建全局异常处理通知类
这里有几个需要注意的点:
- @RestControllerAdvice顾名思义是返回json字符串格式的Controller通知,当然还有@ControllerAdvice注解。
- @ExceptionHandler()括号中写捕捉到的异常类,可以自定义异常,也可以写多个,注意顺序(异常类的范围),应该是按异常子类到父类从上到下排序。
package cool.gjh.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
/**
* 全局异常处理通知类
* <p>
* 注意:返回的是对象的json字符串格式
* </p>
*
* @author ACE_GJH
*/
@RestControllerAdvice
public class ExceptionAdvice {
/**
* 异常处理
* <p>
* 针对捕获的RuntimeException异常类的处理
* </p>
*
* @return
*/
@ExceptionHandler(RuntimeException.class)
public Object runtimeExceptionHandler(Exception e){
HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f);
data.put("code", 501);
data.put("msg", e.getMessage());
data.put("data", null);
data.put("date", System.currentTimeMillis());
return data;
}
/**
* 异常处理
* <p>
* 针对捕获的Exception异常类的处理
* </p>
*
* @return
*/
@ExceptionHandler(Exception.class)
public Object exceptionHandler(Exception e){
HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f);
data.put("code", 502);
data.put("msg", e.getMessage());
data.put("data", null);
data.put("date", System.currentTimeMillis());
return data;
}
}