统一异常拦截处理:RestExceptionHandler
/**
* Created by kaenry on 2016/9/20.
* RestExceptionHandler
*/
@ControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
private <T> RestResult<T> runtimeExceptionHandler(Exception e) {
LOGGER.error("---------> huge error!", e);
return RestResultGenerator.genErrorResult(ErrorCode.SERVER_ERROR);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
private <T> RestResult<T> illegalParamsExceptionHandler(MethodArgumentNotValidException e) {
LOGGER.error("---------> invalid request!", e);
return RestResultGenerator.genErrorResult(ErrorCode.ILLEGAL_PARAMS);
}
}
无论请求成功或失败统一返回RestResult
,可自由定义,比如加上错误code或异常的多次处理以及日志啊什么的,代码都很简单,这里就不详细介绍了,返回的结果类似{"result":true,"message":null,"data":{"id":3,"username":"kaenry","password":"jianshu"}}
,spring-boot
默认使用Jackson
解析拼装json
,如需要忽略null
,加个注解即可:@JsonInclude(JsonInclude.Include.NON_NULL)
,fastjson
默认开启。@Valid
注解会验证属性,不通过会先交给BindingResult
,如果没有这个参数则会抛出异常MethodArgumentNotValidException
,@ExceptionHandler
捕捉到异常则会进入illegalParamsExceptionHandler
方法返回结果:
{
"result": false,
"message": "request params invalid"
}