栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

首先,您应该遵循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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号