哈尔滨网站建设资海,新乡网站,连云港规划建设网站,免费做网站百度能录入在spring 3.2中#xff0c;新增了ControllerAdvice#xff0c;RestControllerAdvice 注解#xff0c;可以用于定义ExceptionHandler、InitBinder、ModelAttribute#xff0c;并应用到所有RequestMapping中。参考帮助文档。RestControllerAdvice 是组件注解#xff0c;他使… 在spring 3.2中新增了ControllerAdviceRestControllerAdvice 注解可以用于定义ExceptionHandler、InitBinder、ModelAttribute并应用到所有RequestMapping中。参考帮助文档。RestControllerAdvice 是组件注解他使得其实现类能够被classpath扫描自动发现如果应用是通过MVC命令空间或MVC Java编程方式配置那么该特性默认是自动开启的。 主要配合ExceptionHandler使用统一处理异常情况。下面的ResponseEntity、ResponseData 都是项目自定义的返回对象。 import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;Slf4j
RestControllerAdvice
public class GlobalExceptionHandler {/*** 处理运行异常*/ExceptionHandler(RuntimeException.class)public ResponseEntityString handleRuntimeException(RuntimeException ex) {log.error(, ex);return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);}/*** 用来捕获404400这种无法到达controller的错误** param ex* return* throws Exception*/ExceptionHandler(value Exception.class)public ResponseData defaultErrorHandler(Exception ex) throws Exception {log.error(, ex);ResponseDataObject result new ResponseDataObject();result.setMessage(ex.getMessage());if (ex instanceof NoHandlerFoundException) {result.setCode(404);} else {result.setCode(500);}result.setData(null);result.setSuccess(false);return result;}
} 转载于:https://www.cnblogs.com/huanshilang/p/10620048.html