src/java/org/myorg/myscserver/ErrorBuilder.java

package org.myorg.myscserver;

import chemaxon.formats.MolFormatException;
import chemaxon.marvin.io.MolExportException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

final class ErrorBuilder {

    private static final String SDF_PARSING_ERROR = "1000";
    private static final String SDF_VALIDATION_ERROR = "1001";
    private static final String SDF_GENERATE_ERROR = "1002";
    private static final String SDF_OTHER_ERROR = "1010";
    private static String template = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><error><error_code>%1$s</error_code><error_details>%2$s</error_details></error>";

    public static String buildErrorResponse(Exception ex) {

        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        String xmlDoc = String.format(template, getErrorCode(ex), sw.toString() );
        return xmlDoc;

    }


    /**
     *
     * Here we decide which exception is mapped to which error code.
     * using this way the client will know what has happened and can take appropriate actions.
     * for example:
     * if(ex instanceof IOException)
     *
     *   return SDF_PARSING_ERROR;
     *
     * @param ex
     * @return
     */
    private static String getErrorCode(Exception ex) {

        if (ex instanceof MolFormatException) {
            return SDF_PARSING_ERROR;
        } else if (ex instanceof MolExportException) {
            return SDF_GENERATE_ERROR;
        } else if (ex instanceof UnsupportedEncodingException) {
            return SDF_VALIDATION_ERROR;
        } else {
            return SDF_OTHER_ERROR;
        }
    }

    private ErrorBuilder() {
        // no-op
    }
}