0
我希望根据响应对象r错误,像400,400,404等动态返回HTTPStatus代码。 Ive提到这个问题 - Programmatically change http response status using spring 3 restful但它没有帮助。根据请求使用@ExceptionHandler动态返回HTTP状态代码
伊夫这个控制器类@ExceptionHandler方法
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(CustomException e) {
return new ResponseEntity<MyErrorResponse>(
new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
ExceptionUtility.getHttpCode(e.getCode()));
}
ExceptionUtility就是我上面使用的两种方法=的getMessage和引用代码
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
我不想签入类如果条件并相应地返回响应代码,是否还有其他更好的方法来执行此操作。
是不是有更好的办法比这个? – user2340345
这是Spring Exception Handler的工作原理。如果你使用春天,你可以用这个。 – Suraj