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

查看:158
本文介绍了在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对象 仅具有一个属性(消息).因此两者能否执行取决于响应.但是摇摇欲坠的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.So可以用@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/

@ 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中发送响应的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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