Search code examples
javarestapiservicecustom-exceptions

My custom exception is not returning the exception code ( code is return 500 always)


I have a strange problem. I have build a custom exception class and i throw that exception in a try catch block. below are my code samples. Please help me to figure out this problems. These are my exception codes.

public class DWExceptionCodes {
public static final int NO_AGENT_FOUND = 400;
public static final int AGENT_ALREADY_EXISTS = 401;
public static final int INCOMPLEATE_DATA = 402;
public static final int SUBSCRIBER_ALREADY_EXISTS = 403;
public static final int AGENT_VALIDATION_FAILED = 404;
public static final int NO_SUBSCRIBER_FOUND = 405;
public static final int TRANSACTION_FAILED = 409;

}

Following is my Exception class

public class DWException extends Exception{
private static final long serialVersionUID= 100L;

private String errorMessage;
private int errorCode;

public String getErrorMessage() {
    return errorMessage;
}
public int getErrorCode(){
    return errorCode;
}
public DWException(String errorMessage) {
    super(errorMessage);
    this.errorMessage = errorMessage;
}
public DWException(String errorMessage, int errorCode) {
    super(errorMessage);
    this.errorMessage = errorMessage;
    this.errorCode=errorCode;
}
public DWException() {
    super();
}

And i have created a custom exception following is that one

public class SubscriberAlreadyExistsException extends DWException{
private static final long serialVersionUID = 1L;
private static String errorMessage = "Subscriber already exists";
private static int errorCode = DWExceptionCodes.SUBSCRIBER_ALREADY_EXISTS;

public SubscriberAlreadyExistsException() {
    super(errorMessage, errorCode);
}

}

this is the place where i throw the exception. This is a restfull web API. But always i got exception in the browser as 500

if (agentService.findByNumberAndPin(agentNumber, pin) != null) {
                if (dbsubscriber != null) {
                    throw new SubscriberAlreadyExistsException();
                }

I cannot figure out what causing this issue. Any quick help is appreciate


Solution

  • The errorCode of your custom Exception class is entirely different from the HTTP response code.

    You need to set the response code manually in your REST controller like:

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    

    While this would work, but this might be a questionable practice to do.