2

My application has javascript button that call Apex code. Exceptions from web services are sometimes thrown and the user is shown a detailed exception message like this:

A problem with the OnClick JavaScript for this button or link was encountered:
{faultcode:'soapenv:Client', faultstring:'HttpException: Example Error Message
Class.BananaWebService.fetchBanana: line 22, column 1', }

Is there a simple way to create friendly error messages for my users when exceptions are thrown like this:

Example Error Message

Exception Class

public class HttpException extends Exception{}

Web Service Class

@RestResource(urlMapping='/BananaWebService/*')
global class BananaWebService {
  webservice static void fetchBanana(Id accountId) {
     throw new HttpException('Example Error Message');
  }
}

Javascript code

{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")} 

var accountId = "{!Account.Id}";
sforce.apex.execute("BananaWebService","fetchBanana", { accountId: accountId }); 
window.location.reload();
2

Use your own try-catch block inside your function:

{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")} 
try {
var accountId = "{!Account.Id}";
sforce.apex.execute("BananaWebService","fetchBanana", { accountId: accountId }); 
window.location.reload();
} catch(e) { alert("I'm sorry. I can't let you do that, Dave. Here's why: \n\n"+(e.message||e)); }

Feel free to customize the error message as you like. You might need to adjust the value for "e", as well.

  • Appreciate the help, this is the best solution as it's outside my actual Apex class and my exception class can be used normally in other situations. – GrayB Dec 13 '13 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.