在Spring Boot中发送响应的最佳实践

编程入门 行业动态 更新时间:2024-10-10 07:31:22
本文介绍了在Spring Boot中发送响应的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在Spring Boot中编写REST Api-s.我想确保使用swagger API开发工具( Swagger ).例如

I'm coding REST Api-s in spring boot. I want to make sure that my code is readable to front-end developers using swagger API development tool (Swagger). For example

@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对象

If the request is successful, response is a Branch object, if fails, the response is a FindError object which has only one attribute (message). So both can be carried out depends on the response. But the swagger UI doesn't show how the response should be shown, because I use "?" as generic type. Is this a best practice to catch an error? (This coding documentation swagger is not useful to front-end developers since it doesn't show the response object). Or any best practice for the above problem?

有很多方法可以返回不同的对象,例如 Branch .预先感谢

There are a lot of method which return different object like Branch. Thanks in advance

推荐答案

首先,您应该遵循RESTful API的最佳实践.不要使用动词,而应使用名词作为URL.So可以用@GetMapping("/getOne")代替 它作为@GetMapping("/branch/{id}"). 您可以在 https:/上引用此博客./blog.mwaysolutions/2014/06/05/10-best-practices-for-better-restful-api/

First of all you should follow the best practices of a RESTful API . Don't use verbs, instead use nouns as URL.So instead of @GetMapping("/getOne") , you can write it as @GetMapping("/branch/{id}") . You can refer this blog blog.mwaysolutions/2014/06/05/10-best-practices-for-better-restful-api/

@ 2nd,不要将通用类型返回为?,而是可以使用特定类型(这里为 Branch )并进行集中式异常处理. 以下代码段可以帮助您:

@2ndly , Don't return a generic type as ? , instead you can user the specific type , here as Branch and do central exception handling . The following code snippet can help you :

@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,您也可以自定义有效负载验证.

The above class handles multiple exceptions including RecordNotFoundException and you can also customize for payload validations too.

测试用例:

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" ] }

更多推荐

在Spring Boot中发送响应的最佳实践

本文发布于:2023-10-12 04:22:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483709.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   Boot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!