Is there any way in apex to show custom error message like 'Invalid Parameter' instead of 'Internal Server Error' when wrong header parameter is passed in postman. I tried using 'throw new exception' things but it didn't help. Any suggestions would be helpful. Thanks!
-
You can do with custom translation in Apex but why you want to do that? Internal Server Error happens when the server encounters an unexpected condition that prevents it from fulfilling the request. So this error doesn't happens only for Invalid Parameter.– Saroj BeraCommented Nov 27, 2023 at 11:54
1 Answer
If you're using a parameterized method, you can't control the error if the data type is invalid. Consider:
@HttpGet public static String method(Id contactId) {
...
}
This code will throw an error before you gain control in Apex if the ID is invalid, for example, if it's only 14 characters. This is true for both webservice
methods and RestResource
classes and methods.
However, if you do your own parsing, you'll gain full control over the response:
@HttpGet public static void method() {
try {
String jsonRequest = RestContext.request.getBody();
...
} catch(Exception e) {
RestContext.response.statusCode = 500;
RestContext.response.responseBody = Blob.valueOf(
JSON.serialize(
new Map<String, Object> {
'success' => false,
'message' => 'Invalid parameter'
}
)
);
}
}
Note that if you allow an uncaught exception to reach the top of the stack, you lose control of the error message. You must not throw an uncaught exception if you want control of the output. Also, note that certain headers can't be caught by Apex, either.
For example, if the Authorization
header is invalid, your code will never get a chance to run. Similarly, if something like the Host
header is invalid, the runtime won't give your Apex code a chance to run. This is in contrast to some frameworks, which just run the desired method, even with invalid data, so that the programmer can control the output.