How can I handle 404's from invalid page requests, but not invalid API responses?

0

Is it possible to handle a 404 differently from a page request than I do a 404 response from a service call?

I want to default to a 404 page if someone requests https://example.com/pagethatdoesnotexist.html. However, I want the 404's returned from https://otherexample.com/api/thing/1 to funnel into my client application so I can give the user a useful message.

I tried using customErrors in my web.config, but it was catching everything. Is this possible or can I only catch all or none with a default 404 page in the config?

Yatrix

Posted 2019-04-30T14:06:55.987

Reputation: 101

Answers

0

What you can do is create a custom 404 page.

On that page, you can put all the logic you need, for example, to handle your API logic, and even changing the responde code to send a 200 instead of a 404.

If something isn't handled by your custom logic, you should send the 404 response code with the following code: (example using PHP)

<?php
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");
?>

Luis Alberto Barandiaran

Posted 2019-04-30T14:06:55.987

Reputation: 225

0

The reason my solution wasn't working was my misunderstanding of custom errors vs http errors. What I was looking for

<httpErrors>
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath="" path="/errorPages/404.html" responseMode="ExecuteURL" />
</httpErrors>

This will catch any bad requests of pages and allow my application to handle 404's coming from api responses.

Yatrix

Posted 2019-04-30T14:06:55.987

Reputation: 101