注册表单,如果电子邮件地址已存在,则使用Spring Boot和JPA抛出异常。

huangapple go评论83阅读模式
英文:

Registration form if email address already exist then throw an exception using Springboot and Jpa

问题

Controller类:

@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 + " already exists");
            }

        }

        User userObject = null;
        userObject = service.saveUser(user);
        return userObject;
    }
}

Repository:

public interface RegistrationRepository extends JpaRepository<User, Integer> {

    public User findByEmailId(String emailId);
}

Service:

@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"
}
英文:

I want to create a form that I can submit it and data store in h2. If email address is already in h2 then throw an exception. I have four packages(Controller, Model, Service, Repository). I dont get my exception message when I use an email that already exist in h2. Can you please help me where is the issue?

Controller class:

@RestController
public class RegistrationController {

	@Autowired
	private RegistrationService service;

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

Repository:

public interface RegistrationRepository extends JpaRepository&lt;User, Integer&gt; {

	public User findByEmailId(String emailId);   
} 

Service:

@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);   
	}
}

Here is JSON response so I want my message printed but somehow not happening:

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

答案1

得分: 0

同样类型的问题我也遇到了。我所做的是,与其在 if 条件内部检查对象,你最好尝试检查对象的属性。
例如:

if (userObject.getEmailId().isEmpty()) {
    throw new Exception("已存在邮箱为 " + tempEmailId + " 的用户");
}

这对我起作用了。

英文:

Same kind of problem i got. what i did is rather than checking the object inside the if condition you better try to check with attribute of the object.
eg
if(userObject.getEmailId().isEmpty()) {
throw new Exception(&quot;User with &quot;+tempEmailId+&quot; is already exist&quot;);
}

this worked for me.

答案2

得分: 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);
  }
}
英文:

You can configure a Spring ExceptionHandler to customize your response body with exception messages:

@ControllerAdvice
public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {


  @Autowired
  public GlobalExceptionMapper() {
  }


  @ExceptionHandler(value = {Exception.class})
  protected ResponseEntity&lt;Object&gt; handleBusinessException(Exception ex, WebRequest request) {

    return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
  }

答案3

得分: 0

如果您正在使用Spring Boot版本2.3或更高版本,则必须在application.properties文件中将属性server.error.include-message设置为always

英文:

If you are using Spring Boot version 2.3 or higher, the property server.error.include-message must be set to always at application.properties file.

huangapple
  • 本文由 发表于 2020年8月26日 15:03:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63592217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定