admin管理员组文章数量:1122846
How should error responses be handled properly? When I need to return a class, I use ResponseEntity<Class>
. However, if I want to return an error as plain text (string), I would need to use ResponseEntity<String>
with string as the return type. What is the best practice in this case? Should I instead map the error to a JSON format
and use ResponseEntity string?
For example I have:
When my return type is Mono<ResponseEntity<UserAccessData>>
, I need to return UserAccessData in successful scenarios. However, when an error occurs, I want to return a ResponseEntity<String>
with an error message. Should I convert all responses, including UserAccessData and error messages, to JSON and set the return type to Mono<ResponseEntity<String>>
? Or is there a better approach to handle this?
@PostMapping("/login")
public Mono<ResponseEntity<UserAccessData>> authorizeUser(@RequestBody @Valid LoginData loginData) {
return userPort.login(loginData)
.map(userAccessData -> ResponseEntity.status(HttpStatus.OK).body(userAccessData))
.onErrorResume(ex -> Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("User authorization failed: " + ex.getMessage())));
}
本文标签: How to Handle Errors with Messages in ResponseEntity in SpringStack Overflow
版权声明:本文标题:How to Handle Errors with Messages in ResponseEntity in Spring? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307384a1933292.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论