Hi there,
Great question! When exposing a codeunit as a web service in Business Central, you're working within the constraints of the OData or SOAP protocols, which unfortunately don't provide native support for custom HTTP status codes like 403 or 400.
Here's what you can do:
1. Custom Status Handling via Response Payload
Since you can't directly change the HTTP status code, a common workaround is to include a custom status field in your response payload. For example:ù
procedure GetResponse(): Text var Response: JsonObject; begin Response.Add('status', 'error'); Response.Add('code', 403); Response.Add('message', 'User not found'); exit(Response.ToString()); end;
This way, the client consuming the service can interpret the status from the payload rather than relying on the HTTP status code.
2. Return JSON Object or Array Instead of String
To return a proper JSON object or array, make sure you're using JsonObject or JsonArray and not converting it to a string unless necessary. If you're using ToString() to return the payload, ensure the consumer parses it correctly as JSON.
Alternatively, if you're using OData, consider exposing a page or query instead of a codeunit, which gives more control over structured data formats.
3. Advanced Option: Use Azure Function or API Management
If you need full control over HTTP status codes and headers, consider wrapping your Business Central logic in an Azure Function or API Management layer. This allows you to call your codeunit internally and expose a more flexible API externally.
Let me know if you'd like help with sample AL code or setting up a wrapper service.
If this answer was helpful, please consider marking it as accepted.
Best regards,
Daniele