SpringBoot的异常处理就是沿用Spring4.x的异常处理,可以参考第十八章 SpringMVC @ControllerAdvice
单个controller范围的异常处理
@RestController
public class AdviceController {
@ExceptionHandler(RuntimeException.class)
public ExceptionResponse exceptionHandler() {
return new ExceptionResponse("1001", "系统繁忙")
}
}
全局异常处理
package com.container.web.handler;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
private void defaultErrorHandler(HttpServletRequest req, Exception e) {
log.error("catch exception by global exception handler");
e.printStackTrace();
}
}