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