Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
How to catch custom java8 exception from react?

Following code generates exception as UserAlreadyExist.

Optional<User> userCheck = userRepository.findByUsername(createRequest.getUsername());
    if(StringUtils.hasText(userCheck.get().getUsername())){
        String errorMessage = "User already exist: "+ userCheck.get().getUsername();
        throw new UserAlreadyExistException(errorMessage);
    }

When i try to get error message from my react app with these codes i only get Internal server error message. My header contains header token and application/JSON header.

export const createUserService = (data) => {
return new Promise(((resolve, reject) => {
    axios.post(USERS_BASE, data, getHeaderWithToken())
        .then(function (response) {
            resolve(response);
        })
        .catch(error=>{
        console.log(error)//returns "Internal Server Error" message
        console.log(error.response) // returns object with empty message field and other parameters.
            reject(error)
    })
}));

};

How can i get the error message i sent like

String errorMessage = "User already exist: "+ userCheck.get().getUsername();
        throw new UserAlreadyExistException(errorMessage);
    

this is my UserAlreadyExistException class btw.

public class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(String message) {
    super(message);
    
}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can return custom Response with @RestControllerAdvice for the custom exception you are throwing. Please check the example below.

 @RestControllerAdvice
    public class ControllerExceptionHandler {
      
  @ExceptionHandler(value = {UserAlreadyExistException.class})
  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  public ErrorMessage userAlreadyExistException(UserAlreadyExistException ex, WebRequest request) {
    ErrorMessage message = new ErrorMessage(
        status,
        date,
        ex.getMessage(),
        description);
    
    return message;
  }
}

It will be much easier for you to see the error in your Frontent application with a Response that you will return like this.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!