Java – Custom Light Exceptions

Java – Custom Light Exceptions

 

 

Java – Custom Light Exceptions

by Hyun Woo Son – Software Architect

For custom exceptions we will adhere to spring rules for exceptions so first extends RuntimeException


public class CustomException extends RuntimeException 

This will not force a method to throw the exception or catch it on the calling class, making more clean our code but we will have to take care of it on the most upper level, if the case its a rest it should be catch it there and transform it to an most friendly response to the user.

The second thing its to pass on the constructor this parameters to make our exception light and to do just the specific error.

 super(message,null,false,false);

This on the parent class are:


 protected RuntimeException(String message, Throwable cause,
                               boolean enableSuppression,
                               boolean writableStackTrace)

We just want the message to go and the break of the flow of our running program, so first we null the Throwable cause indicating is nonexistent.

Then false the enableSuppression to avoid having suppressed exceptions on our custom exceptions, in a try catch and finally block it could be the case where on the finally block is throwing another exception instead of the exception on the try catch the compiler will choose the finally thrown exception.

This example was found on stackoverflow.


public class SuppressedExceptions {
  public static void main(String[] args) throws Exception {
    try {
        callTryFinallyBlock();
    } catch (Exception e) {
        e.printStackTrace(); **//Only Finally Exception is Caught**
    }
  }

  private static void callTryFinallyBlock() throws Exception {
    try 
    {
        throw new TryException(); **//This is lost**
    }
    finally
    {
        FinallyException fEx = new FinallyException();
        throw fEx;
    }
  }
}

This will cause supressed exceptions to be added on the finally exception , the parameter on false will cause this exceptions to not be added.

And finally we will false the writableStackTrace to disable the stacktrace to be writable. Each throwable constructor calls fillInStackTrace() so it wont be invoked

On the constructor side we will not have a default empty constructor to force the message to be present.

Also we could add Message.format to our exception to avoid concatenating strings.

public CustomException(String msg, Object ...vars){
        super(MessageFormat.format(msg,vars),null,false,false);
    }

Notice we have the …vars our varargs parameters to add any parameters to be added to the string, so we can call it like this.

throw new CustomException("The error is {0} and was caused by {1}","grave","me");

The order of the parameters will go on the string by the position on the varargs.

The complete class will look like:

import java.text.MessageFormat;

/**
 * Created by .... on 9/18/19
 **/
public class CustomException extends RuntimeException {


    public CustomException(String message) {
         super(message,null,false,false);  
    }

    public CustomException(String msg, Object ...vars){
        super(MessageFormat.format(msg,vars),null,false,false);
    }
    

And called like:

    
    private void ourFunction()
    {
    ...custom..code
    throw new CustomException("The error is {0} and was caused by {1}","grave","me");
    ...more custom ..code
    }
    
    // and called like:
    
    
    ... custom code on our rest...
    try{
    ourFunction();
    moreFunctions();
    }
    catch(CustomException e){
        //log just the message
        log.error("Error {}",e.getMessage());
        throw new ResponseStatusException(HTTPStatus.BAD_REQUEST,e.getMessage());   
    }
    ... custom code...
    
    
    // or we can add to more cleanly just add on spring an controller advice handling our error.

 

 

Leave a Reply

Your email address will not be published.

Advance Latam
Cuéntenos su proyecto y permítanos ayudarle.