SpringMVC异常错误默认返回如
{
"timestamp": 1505491515460,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'param' is not present",
"path": "/he"
}
如何定制呢?
定义model
public class DTO<T> {
private Integer code;
private String msg;
private T data;
public DTO(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
定义ControllerAdvice
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
return super.handleExceptionInternal(ex, new DTO(status.value(), ex.getMessage()), headers, status, request);
}
@ExceptionHandler(Throwable.class)
public ResponseEntity<DataBean> handleOtherThrowable(Exception exception) {
return new ResponseEntity(new DTO(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
}
}
查看结果
{
"code": 400,
"msg": "Required String parameter 'param' is not present"
}
关键是在ResponseEntityExceptionHandler
这个类上