Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda