Sunday, November 5, 2017

Apache Commons ContextedException

Developers often forget to attach context information to their exceptions. So one gets messages like "Unable to connect to server" and we don't know to which server and port the connection was attempted.

Add this to your pom.xml

  <!-- -->

and this is the test code

package pvexceptions;

import org.apache.commons.lang3.exception.ContextedException;;

public class PVExceptionGenerator {
 public static void main(String[] args) {
  try {
   try {
    int a = 1 / 0;
   } catch (Throwable a) {
    throw new ContextedException("something went wrong in division", a).addContextValue("customer", "Mario").addContextValue("custno", 1234);

  } catch (Throwable t) {


The output is:

org.apache.commons.lang3.exception.ContextedException: something went wrong in division
Exception Context:
at pvexceptions.PVExceptionGenerator.main(
Caused by: java.lang.ArithmeticException: / by zero
at pvexceptions.PVExceptionGenerator.main(

No comments: