我正在Spring Boot中编写REST Api-s。我想确保使用swagger API开发工具(Swagger)的前端开发人员可以阅读我的代码。例如
@GetMapping("/getOne")
public ResponseEntity<?> getOne(@RequestParam String id) {
try {
return new ResponseEntity<Branch>(branchService.getOne(id), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<FindError>(new FindError(e.getMessage()), HttpStatus.BAD_REQUEST);
}
}
如果请求成功,则响应为 分支对象 ;如果失败,则响应为 FindError对象 仅具有一个属性(消息)。因此两者能否执行取决于响应。但是摇摇欲坠的UI并未显示应如何显示响应,因为我使用“?” 作为通用类型。这是捕获错误的最佳实践吗? (此编码文档说明对前端开发人员没有用,因为它没有显示响应对象)。或针对上述问题的最佳做法?
有很多方法可以返回不同的对象,例如 Branch 。预先感谢
答案 0 :(得分:3)
首先,您应该遵循RESTful API的最佳实践。不要使用动词,而应使用名词作为URL。因此,您可以编写@GetMapping("/getOne")
而不是{
它为@GetMapping("/branch/{id}")
。
您可以引用此博客https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/
@ 2ndly,不要返回泛型类型为?,而是可以使用特定类型(这里为 Branch )并进行集中式异常处理。 以下代码段可以为您提供帮助:
@GetMapping("/branch/{id}")
public ResponseEntity<Branch> getBranch(@Pathvariable String id) {
{
Branch branch = branchService.getOne(id);
if(branch == null) {
throw new RecordNotFoundException("Invalid Branch id : " + id);
}
return new ResponseEntity<Branch>(branch, HttpStatus.OK);
}
RecordNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException
{
public RecordNotFoundException(String exception) {
super(exception);
}
}
CustomExceptionHandler.java
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(RecordNotFoundException.class)
public final ResponseEntity<Object> handleRecordNotFoundException(RecordNotFoundException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Record Not Found", details);
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
}
ErrorResponse.java
public class ErrorResponse
{
public ErrorResponse(String message, List<String> details) {
super();
this.message = message;
this.details = details;
}
private String message;
private List<String> details;
//Getter and setters
}
上面的类处理多个异常,包括RecordNotFoundException,您也可以自定义有效载荷验证。
测试用例:
1) HTTP GET /branch/1 [VALID]
HTTP Status : 200
{
"id": 1,
"name": "Branch 1",
...
}
2) HTTP GET /branch/23 [INVALID]
HTTP Status : 404
{
"message": "Record Not Found",
"details": [
"Invalid Branch id : 23"
]
}
答案 1 :(得分:0)
我建议这样做。
@GetMapping("/getOne")
public Response getOne(@RequestParam String id) {
ResponseEntity<Branch> resbranch;
ResponseEntity<FindError> reserror;
try {
resbranch=new ResponseEntity<Branch>(branchService.getOne(id), HttpStatus.OK);
return Response.status(200).entity(resbranch).build();
} catch (Exception e) {
reserror=new ResponseEntity<FindError>(new FindError(e.getMessage()), HttpStatus.BAD_REQUEST);
return Response.status(400).entity(reserror).build();
}
}
200表示正常,400表示错误。这里将不再有歧义类型。.