I’m coding a custom exception where if the username already exists, the response will be the custom exception, i.e., UserException in json.
UsernameAlreadyExistException.java
package com.crawler.exception;
public class UsernameAlreadyExistException extends RuntimeException {
public UsernameAlreadyExistException(String message) {
super(message);
}
public UsernameAlreadyExistException(String message, Throwable cause) {
super(message, cause);
}
}
UserException.java
package com.crawler.exception;
import org.springframework.http.HttpStatus;
public class UserException {
private final String message;
private final Throwable throwable;
private final HttpStatus httpStatus;
public UserException(String message, Throwable throwable, HttpStatus httpStatus) {
this.message = message;
this.throwable = throwable;
this.httpStatus = httpStatus;
}
public String getMessage() {
return message;
}
public Throwable getThrowable() {
return throwable;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
UserExceptionHandler
package com.crawler.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(value = {UsernameAlreadyExistException.class})
public ResponseEntity<Object> handleUsernameAlreadyExistException(UsernameAlreadyExistException usernameAlreadyExistException) {
UserException userException = new UserException(
usernameAlreadyExistException.getMessage(),
usernameAlreadyExistException.getCause(),
HttpStatus.CONFLICT
);
return new ResponseEntity<>(userException, HttpStatus.CONFLICT);
}
}
In the service implementation, I coded to throw a UsernameAlreadyExistException.
UserServiceImplementation.java
@Override
public String createUser(User user) {
if (userRepository.findByUsername(user.getUsername()) != null) {
throw new UsernameAlreadyExistException("Username already exist.");
}
userRepository.save(user);
return "User created successfully.";
}
This is the output from the console.
2024-09-24T13:41:43.809Z ERROR 1 --- [backend] [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.crawler.exception.UsernameAlreadyExistException: Username already exist.] with root cause
The response from POSTMAN.
{
"timestamp": "2024-09-24T13:41:43.878+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/users"
}
Expected response from POSTMAN.
{
"message": "Username already exist",
"throwable": null,
"httpStatus": "CONFLICT"
}
3