How to resolve the error - System.UnexpectedException: Script-thrown exception?

2.7K    Asked by DavidEdmunds in Salesforce , Asked on May 15, 2023

I'm trying to create an Apex callout and running into the following error message: System.UnexpectedException: Script-thrown exception My analysis shows that System.UnexpectedException is not catchable in Apex. There are some reports of exceptions with “Script-thrown exception” message by other users, but the exception type in those cases happen to be System.CalloutException. [1] The only reported case of a System.UnexpectedException with the same message appears to be triggered by log level of Callouts. (Note: the recommended workaround did not solve the problem in our case.) [2]

This is the code that causes the error:

HttpRequest req = new HttpRequest(); req.setEndpoint('callout:AmazonConnectAPI/contact/start-recording'); req.setMethod('POST'); String body = String.format( ''{'"ContactId": "{0}","InitialContactId": "{1}","InstanceId": "{2}","VoiceRecordingConfiguration": '{'"VoiceRecordingTrack": "{3}"'}''}'', new List{ contactId, initialContactId, instanceId, voiceRecordingTrack } ); if (body != '') { req.setBody(body); } Http http = new Http(); HttpResponse resp = http.send(req);

Other notable facts:

  • The HTTP callout is made to a Named Credential called AmazonConnectAPI
  • AmazonConnectAPI is configured for "https://connect.us-east-1.amazonaws.com“
  • The authentication method of the Named Credential is Named Principal with protocol "AWS Signature Version 4
  • The authentication method uses the credentials for an IAM user with a full-access managed policy to Amazon Connect.
  • The formatting of the body is correct. There is no syntax error.
  • The error comes from this line HttpResponse resp = http.send(req);



Answered by Dipika Agarwal

I was having some issues with my Named Credential (Named Principal) AWS Signature Version 4 and found some resolutions for the below error: HttpResponse resp = http.send(req); System.UnexpectedException: Script-thrown exception

1. Named Credential Name

      Double check your 'callout:Named_Credential' in Apex matches the Named Credential API 'Name'.

No brainer, but it got me for a few hours.

2. URL Encoded Endpoint

Make sure to escape any URL reserved characters: https://developers.google.com/maps/documentation/urls/url-encoding.
String endpoint = 'callout:Named_Credential/contactId/start=2021-02-10Thh:mm:ss.msm-00:00';
Should probably be:
String endpoint = 'callout:Named_Credential/contactId/start=2021-02-10Thh:mm:ss.msm-00:00';
No brainer, but it got me for a few more hours.
3. Escaping Curly Braces in String.format()
I just ran this in Dev Console for your body and got the below:
System.debug((Map) JSON.deserializeUntyped(String.format( ''{'"ContactId": "{0}","InitialContactId": "{1}","InstanceId": "{2}","VoiceRecordingConfiguration": '{'"VoiceRecordingTrack": "{3}"'}''}'', new List{ 'contactId', 'initialContactId', 'instanceId', 'voiceRecordingTrack' } ))); 15:46:47:008 FATAL_ERROR System.JSONException: Unexpected character (''' (code 39)): was expecting comma to separate OBJECT entries at [line:1, column:171]
Changing the last few escaped curly braces from "{3}"'}''}'', to "{3}"'}'}', got me a correct string
System.debug((Map) JSON.deserializeUntyped(String.format( ''{'"ContactId": "{0}","InitialContactId": "{1}","InstanceId": "{2}","VoiceRecordingConfiguration": '{'"VoiceRecordingTrack": "{3}"'}'}', new List{ 'contactId', 'initialContactId', 'instanceId', 'voiceRecordingTrack' } ))); 15:40:31:006 USER_DEBUG [45]|DEBUG|{ContactId=contactId, InitialContactId=initialContactId, InstanceId=instanceId, VoiceRecordingConfiguration={VoiceRecordingTrack=voiceRecordingTrack}}

Your Answer

Answers (6)

Thanks for sharing this! It's interesting how sometimes debugging feels like the iq test - solving puzzles to uncover the root cause. I'll definitely double-check the Named Credential name and the URL encoding!

3 Weeks

To resolve the System.UnexpectedException: Script-thrown exception error in your Apex callout, you should consider several potential issues and debugging steps. 

Ensure the JSON body of the request is correctly formatted. You are using String.format dinosaur game, which is correct, but sometimes the escaping of quotes can be tricky. Verify the final JSON structure:

String body = String.format(

    ''{'"ContactId": "{0}","InitialContactId": "{1}","InstanceId": "{2}","VoiceRecordingConfiguration": {'"VoiceRecordingTrack": "{3}"}}'}'',

    new List { contactId, initialContactId, instanceId, voiceRecordingTrack }

);

3 Months

That is, as Ranjana said. Must carry out Locate the Code Object Look over the script -> Review Debugging Data and Logs ->Deal with Errors ->Run the script test ->Recurrence Monitoring -> gorilla tag



4 Months

As Ranjana mentioned. Need to perform Identify the Script-> Review the Script-> Check Logs and Debugging Information->Handle Exceptions->Test the Script->Monitor for Recurrence->

And finally wait for the results of fish eat fish

5 Months

The error message "System.UnexpectedException: Script-Thrown Exception" typically indicates that an unexpected exception occurred in a script. To resolve this error, you'll need to identify the script causing the exception and then address the issue causing the exception. Here are some general steps you can take:


Identify the Script: Determine which script is causing the exception. This could be a script written in a programming language such as JavaScript, Python, or Apex, depending on the context in which you encountered the error.

Review the Script: Carefully review the code in the script to identify any potential issues such as syntax errors, logic errors, or unexpected behavior. Look for any lines of code that could be causing the exception.

Check Logs and Debugging Information: Look for any logs, error messages, or debugging information that can provide more context about the exception. This may include stack traces, error codes, or additional details about where the exception occurred.

Handle Exceptions: If the script is written in a language that supports exception handling (such as try-catch blocks in JavaScript or Python), consider adding exception handling code to catch and handle any potential errors gracefully. This can help prevent the script from crashing and provide more meaningful error messages to users.

Test the Script: Once you've identified and addressed the issue causing the exception, test the script to ensure that the error no longer occurs. Verify that the script behaves as expected and that it handles any potential errors or edge cases correctly.

Monitor for Recurrence: Keep an eye on your system to ensure that the error does not recur. Monitor logs and error reports for any signs of the exception reoccurring, and be prepared to investigate and address any new issues that arise.

By following these steps and thoroughly investigating the cause of the "System.UnexpectedException: Script-Thrown Exception" error, you should be able to resolve the issue and prevent it from affecting your system in the future.

6 Months

To add to "1. Named Credential Name", this exception may occur when a callout refers to named credentials that are part of a package with a namespace. Even if APEX code is included in the same package.


When this occurs, the callout works in a Development org with the same namespace as the package containing the named credentials, but it throws "System.UnexpectedException: Script-thrown exception" when deployed basketball stars to a different namespace. So you only need to add the package namespace to the callout.

HttpRequest req = new HttpRequest();
req.setEndpoint('callout:__/some-path');
6 Months

Interviews

Parent Categories