首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用restfulAPI使用SpringBoot发送错误消息

如何使用restfulAPI使用SpringBoot发送错误消息
EN

Stack Overflow用户
提问于 2020-10-03 17:40:58
回答 1查看 666关注 0票数 0

我有一个使用SpringBoot和restful构建的服务器,它是一个简单的CRUD应用程序。

我试图检查电子邮件是否已经存在,同时添加一个新的用户。

我不知道如何通过rest发送错误消息。我试过这样做:

UserController.java

代码语言:javascript
复制
  //POST method for adding one user
    @PostMapping("/addUser")
    public ResponseEntity<User> addUser(@RequestBody User user){
        User existingUser = userRepository.findByEmail(user.getEmail());
        if(existingUser != null){
            throw new UserAlreadyExistException("User with this email already exists");
        }
        return new ResponseEntity<>(service.saveUser(user), HttpStatus.OK) ;
    }

UserAlreadyExistException.java

代码语言:javascript
复制
public class UserAlreadyExistException extends RuntimeException{

    public UserAlreadyExistException(String message) {
        super(message);
    }

}

当我用邮递员测试它时,我得到了Error: 500 Internal Server Error

InteliJ中,我引发了这个异常:

使用此电子邮件的com.example.library.UserAlreadyExistException:用户

已经存在

这是一种正确的做法,还是什么是最佳实践?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-03 17:55:54

你要找的是@ControllerAdvice@ExceptionHandler。处理此类异常的方式如下:

@ControllerAdvice

  • Catch
  1. 创建全局异常处理程序,并在特定于特定异常的方法中使用@ExceptionHandler对异常进行注释。

因此,添加下面的代码将捕获异常并返回自定义响应。

代码语言:javascript
复制
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<Object> handleAuthenticationException(UserAlreadyExistException e) {
        // do what you want with e
        return new ResponseEntity<>("User already exists", HttpStatus.OK);
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64187162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档