1.全局捕获异常处理器
代码如下:
package com.example.exceptiondemo.error;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* create by
*
* @Author luozhiyuan
* @qq 707530775@qq.com
* @on 2019-06-30.
* @time 11:17
*/
@ControllerAdvice("com.example.exceptiondemo.controller")
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<String,Object> errorResult(){
Map<String,Object> errorResultMap = new HashMap<>();
errorResultMap.put("errorCode","500");
errorResultMap.put("errorMsg","全局捕获异常!");
return errorResultMap;
}
}
2.抛出异常的controller
package com.example.exceptiondemo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* create by
*
* @Author luozhiyuan
* @qq 707530775@qq.com
* @on 2019-06-30.
* @time 14:48
*/
@RestController
public class ErrorController {
@RequestMapping("/getUser")
public String getUser(Integer i){
Integer j = 1 / i;
return "success"+j;
}
}