How Do I: Handle Errors In a Web Service?

Some web service errors cannot be detected at compile time. For example, your code may attempt to call a method on a null reference or it may invoke a Database control that attempts to execute some invalid SQL. In most cases, an error at run time will cause an exception to be thrown. Unless you add code to handle the exception, this will cause a SOAP fault to be sent back to the client. Unhandled exceptions also cause rollback of a web service's implicit transaction.

You may want to override the default exception handling and perform a custom action, such as logging an error so that an administrator will know the problem occurred.

There are two ways that you can write code to handle exceptions. The first way is to add try/catch blocks around the code in your method. For example, to catch all exceptions that are thrown in your method "myMethod," you would write this:

    /**
     * @jws:operation
     */
    public void myMethod()
    {
        try
        {
            // [ Normal code for the method. ]
        }
        catch (Exception e)
        {
            // [ Code to handle error cases. ]
        }
    }

If an exception is thrown at any point during the execution of the normal code of the method, the code in the "catch" block will be executed.

One disadvantage of this is that it only works for "myMethod." So if you want to implement exception handling for all of your methods, you have to add try/catch blocks into every method.

The second way to handle exceptions is to add a handler for the "onException" callback of the JwsContext interface. Unlike try/catch blocks, this code will be executed when an exception is thrown in any of the methods of your web service.

To Add a General Handler for Run-Time Exceptions

1. In Source View, just beneath the Source View tab, click the left-hand class drop-down list, then click context.

2. Click the right-hand drop-down list at the top of the pane, then click onException.

This will insert a handler named context_onException into your web service.

3. Write your custom exception handling code into the body of this method. It will be executed whenever an exception occurs in one of your methods.

For further information on Java exceptions, see the Java language tutorial at java.sun.com/docs/books/tutorial/essential/exceptions/index.html.

# Writing to Log Files

WebLogic Workshop has pre-configured log files to which you can write messages. To learn about the pre-configured log files and how to write to them, see workshopLogCfg.xml Configuration File.

Related Topics

Introduction to Java

Default Transactional Behavior in WebLogic Workshop