SpringMVC 统一处理exception

jopen 10年前

用 @ExceptionHandler注解实现异常统一处理:

public class BaseController {         private static final Logger logger = LoggerFactory.getLogger(BaseController.class);         @ExceptionHandler(Exception.class)      @ResponseBody         protected ResponseVo handleException(Exception e) {          logger.error(e.getMessage(), e);          if (e instanceof HttpMessageNotReadableException ||                  e instanceof NumberFormatException ||                  e instanceof InvalidPropertyException){              return new ResponseVo(ResponseStatus.DATA_PARSE_ERROR.VALUE, e.getLocalizedMessage());          } else if (e instanceof NoticeException) {              return new ResponseVo(ResponseStatus.FORBIDDEN.VALUE, e.getMessage());          }          return new ResponseVo(ResponseStatus.ERROR.VALUE,e.getLocalizedMessage());      }     }

如果程序异常会被捕获,接下来响应的数据就可以自己定义了