//捕获当前类中所有的Exception异常
@ExceptionHandler(Exception.class)
public @ResponseBody
Map<String, Object> InterruptedExceptionHandler(InterruptedException interruptedException) {
logger.error(interruptedException.getMessage());
Map<String, Object> model = new TreeMap<>();
model.put("INTERRUPTED_EXCEPTION", interruptedException.getMessage());
return model;
}
捕获异常返回页面,添加备注信息提供详
--------------------------------------------------------------------------------------------------------------
异常处理代码
@RestControllerAdvice注解
@ControllerAdvice注解
@ControllerAdvice
public class MyControllerAdvice {
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("author", "Magical Sam");
}
/**
* 全局异常捕捉处理
* @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;
}
}
取值----
@RequestMapping("/home")
public String home(ModelMap modelMap) {
System.out.println(modelMap.get("author"));
}
//或者 通过@ModelAttribute获取
@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {
System.out.println(author);
controller
直接抛出对应异常类
throw new EnforcementServiceException("任务类型错误");
异常类
public class EnforcementServiceException extends RuntimeException {
public EnforcementServiceException(String message) {
super(message);
}
public EnforcementServiceException(String msg, Throwable cause) {
super(msg, cause);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
public Throwable doFillInStackTrace() {
return super.fillInStackTrace();
}
}
handler
@ExceptionHandler(EnforcementServiceException.class)
public ResultData handleError(EnforcementServiceException e, HttpServletResponse response) {
log.error("业务异常", e);
if(e.getMessage().equals(String.valueOf(HttpStatus.HTTP_UNAUTHORIZED))) {
response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
}
return ResultData
.builder()
.code(ResultData.SuccessEnum.SUCCESS_200.getCode())
.status(ResultData.ErrorEnum.ERROR.getCode())
.message(e.getMessage())
.success(false)
.build();
}