2

我想创建一个表单,我可以提交它并将数据存储在 h2 中。如果电子邮件地址已经在 h2 中,则抛出异常。我有四个包(控制器、模型、服务、存储库)。当我使用 h2 中已经存在的电子邮件时,我没有收到异常消息。你能帮我解决问题吗?

控制器类:

@RestController
public class RegistrationController {

    @Autowired
    private RegistrationService service;

    @PostMapping("/registeruser")
    public  User registerUser(@RequestBody User user) throws Exception {
        
        String tempEmailId = user.getEmailId();
        if(tempEmailId !=null && !"".equals(tempEmailId)) {
            User userObject = service.fetchUserByEmailId(tempEmailId);
            if(userObject!=null) {
                throw new Exception("User with "+tempEmailId+" is already exist");
            }
            
        }
            
        User userObject = null;
        userObject = service.saveUser(user);
        return userObject;
    }

存储库:

public interface RegistrationRepository extends JpaRepository<User, Integer> {

    public User findByEmailId(String emailId);   
} 

服务:

@Service
public class RegistrationService {

    @Autowired 
    private RegistrationRepository repo;
    
    public User saveUser(User user) {
        return repo.save(user);
    }
    
    public User fetchUserByEmailId(String email) { 
        return repo.findByEmailId(email);   
    }
}

这是 JSON 响应,所以我希望打印我的消息,但不知何故没有发生:

{
    "timestamp": "2020-08-26T06:28:01.369+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/registeruser"
}
4

3 回答 3

0

我遇到了同样的问题。我所做的不是检查 if 条件内的对象,而是最好尝试检查对象的属性。例如 if(userObject.getEmailId().isEmpty()) { throw new Exception("User with "+tempEmailId+" is already exist"); } ,这对我有用。

于 2020-08-26T07:24:52.477 回答
0

您可以配置 Spring ExceptionHandler以使用异常消息自定义响应正文:

@ControllerAdvice
public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {


  @Autowired
  public GlobalExceptionMapper() {
  }


  @ExceptionHandler(value = {Exception.class})
  protected ResponseEntity<Object> handleBusinessException(Exception ex, WebRequest request) {

    return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
  }
于 2020-08-26T07:25:08.980 回答
0

如果您使用的是 Spring Boot 2.3 或更高版本,则该属性server.error.include-message必须设置为alwaysat application.propertiesfile。

于 2020-09-13T03:20:50.360 回答