I want to write custom exception handling for my java code. I am using rest based service which returns a valid json response in case of success. In case of any exception, I want to return a proper json response with the error code and error message.
This is my Exception class
public class MyException extends Exception{
private static final long serialVersionUID = -6823908633735492805L;
protected String errorCode;
protected String errorMessage;
public MyException()
{
super();
}
public MyException(String errorCode)
{
super(errorCode, null);
this.errorCode = errorCode;
}
public MyException(String errorMessage, String errorCode)
{
this.errorMessage = errorMessage;
this.errorCode = errorCode;
}
public MyException(String message, Throwable cause)
{
super(message, cause);
}
public MyException(Throwable cause)
{
super(cause);
}
public String getErrorCode()
{
return errorCode;
}
public String getErrorMessage()
{
return errorMessage;
}
public MyException(Throwable cause, String errorCode, String errorMessage)
{
super(cause);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
In my code, i am handling the Exception like below but I am getting 500 Internal Server Error
}catch(IllegalArgumentException e) {
throw new MyException("301",e.getMessage());
}
Below is my rest api
@Path("{id}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Operation(operationId = "update")
@APIResponse(responseCode = "204")
public Response update(@Context SecurityContext context, String effort) throws MyException {
try {
service.update(effort);
return Response.noContent().build();
}catch(IllegalArgumentException e) {
throw new MyException("301",e.getMessage());
}
}
Any help is appreciated.. Thanks in advance
Exception. You have to inheritRuntimeException.