在 Spring Boot 中发送响应的最佳实践 [英] Best practice to send response in spring boot

查看:30
本文介绍了在 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);
        }
    }

如果请求成功,response是一个Branch object,如果失败,response是一个FindError object 只有一个属性(message).所以两者能否进行取决于响应.但是招摇的 UI 没有显示响应应该如何显示,因为我使用 "?" 作为通用类型.这是捕获错误的最佳实践吗?(这个编码文档招摇对前端开发人员没有用,因为它不显示响应对象).或者针对上述问题的任何最佳实践?

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.所以你可以写而不是 @GetMapping("/getOne")它是 @GetMapping("/branch/{id}") .你可以参考这个博客https:///blog.mwaysolutions.com/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 https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

@2ndly,不要将泛型类型返回为 ? ,您可以使用特定类型,此处为 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 中发送响应的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆