Include exception message in JSON error response

Viewed 1911

If email address already exists then throw an exception with a message("message:"User with "+tempEmailId+" already exists"). I don't get my exception message when I test in postman. Can you please help me ? Where is the issue? enter image description here

Controller class:

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

    }
}

Repository:

public interface RegistrationRepository extends JpaRepository<User, Integer> {

    public User findByEmailId(String emailId);  // Here we declare 
}  

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);   
    }
}
2 Answers

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

Quoted from Spring Boot 2.3 Release Notes:

Changes to the Default Error Page’s Content

The error message and any binding errors are no longer included in the default error page by default. This reduces the risk of leaking information to a client. server.error.include-message and server.error.include-binding-errors can be used to control the inclusion of the message and binding errors respectively. Supported values are always, on-param, and never.

You can wrap your controller responses to ResponseEntity.

@PostMapping("/registeruser")
public  ResponseEntity<Object> registerUser(@RequestBody User user) throws Exception {
        String tempEmailId = user.getEmailId();
        if(tempEmailId != null && !tempEmailId.isEmpty()) {
            User userObject = service.fetchUserByEmailId(tempEmailId);
            if(userObject!=null) {
                return new ResponseEntity<>("User with "+tempEmailId+" is already exist", HttpStatus.BAD_REQUEST);
            }
        }
        return new ResponseEntity<>(service.saveUser(user), HttpStatus.OK);
}

Or (preferable variant) your can create specific exception, for example UserAlreadyExistException, throw it in controller and intercept in class annotated with @RestControllerAdvice. For example:

@RestControllerAdvice
public class RegistrationControllerAdvice {

    @ExceptionHandler({UserAlreadyExistException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String userAlreadyExist(UserAlreadyExistException ex, WebRequest req) {
        return ex.getMessage();
    }
}

Instead of String you can return any data structure serializable to JSON.

Related