oyg*_*gen 6 java rest spring controller spring-boot
我正在制作一个简单的休息服务,它使用 RestTemplate 进行一些 http 调用并聚合数据。
有时我会收到 NotFound 错误,有时会收到 BadRequest 错误。
我想用相同的状态代码响应我的客户端,Spring 似乎已经提供了这种开箱即用的映射。消息正常,但状态代码始终为 500 内部服务器错误。
我想将我的状态代码映射到我最初收到的状态代码
"timestamp": "2019-07-01T17:56:04.539+0000",
"status": 500,
"error": "Internal Server Error",
"message": "400 Bad Request",
"path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}
Run Code Online (Sandbox Code Playgroud)
我希望是这样
"timestamp": "2019-07-01T17:56:04.539+0000",
"status": 400,
"error": "Internal Server Error",
"message": "400 Bad Request",
"path": "/8b8a38a9-a290-4560-84f6-3d4466e8d7901"
}
Run Code Online (Sandbox Code Playgroud)
它抛出 HttpClientErrorException.BadRequest 或 HttpClientErrorException.NotFound
我的代码是一个简单的端点:
@GetMapping("/{id}")
public MyModel getInfo(@PathVariable String id){
return MyService.getInfo(id);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用注释创建全局异常处理@ControllerAdvice。像这样:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = YourExceptionTypes.class)
protected ResponseEntity<Object> handleBusinessException(RuntimeException exception, WebRequest request) {
return handleExceptionInternal(exception, exception.getMessage(), new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE, request);
}
}
Run Code Online (Sandbox Code Playgroud)
当抛出异常时,处理程序将捕获并将其转换为所需的响应。原始异常不会被传播。
| 归档时间: |
|
| 查看次数: |
8619 次 |
| 最近记录: |