/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.remote.server.renderer;

import org.openqa.selenium.remote.BeanToJsonConverter;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.server.rest.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonErrorExceptionResult extends ErrorJsonResult {
  private final String exceptionName;

  public JsonErrorExceptionResult(String exceptionName, String responseOn) {
    super(responseOn);
    this.exceptionName = exceptionName.substring(1);
  }

  public void render(HttpServletRequest request, HttpServletResponse response, Handler handler)
      throws Exception {
    Exception e = (Exception) request.getAttribute(exceptionName);

    Response res = new Response();
    res.setError(true);

    String raw = new BeanToJsonConverter().convert(e);
    if (raw.startsWith("{")) {
      res.setValue(String.format("{ screen: \"%s\", %s",
                   request.getAttribute("screen"), raw.substring(1))); 
    } else {
      res.setValue(raw);
    }

    request.setAttribute(propertyName, res);

    super.render(request, response, handler);
  }
}

@@ -805,16 +805,44 @@
 Handler;
+%0Aimport org.json.JSONObject;
 %0A%0Aimport
@@ -1494,16 +1494,60 @@
 ert(e);%0A
+    JSONObject error = new JSONObject(raw);%0A
     if (
@@ -1579,77 +1579,27 @@
     
-res.setValue(String.forma
+error.pu
 t(%22
-%7B 
 screen
-: %5C%22%25s%5C%22, %25s%22,%0A                  
+%22,
  req
@@ -1629,46 +1629,17 @@
 en%22)
-, raw.substring(1))
 );
- 
 %0A    %7D
- else %7B%0A  
+%0A
     
@@ -1655,19 +1655,26 @@
 lue(
-raw);%0A    %7D
+error.toString());
 %0A%0A  

Use the JSON libraries to create the response string.