简体   繁体   中英

Best way to return added value on Http Status Code 404

At times I return, at server level, some extra information alongside with a HTTP 404

For example, instead of returning just a 404 , which can puzzle my client whether the routing is correct or not, it will also receive something like

the identifier 'abc' is unknown

I usually set the content type to text/plain and return some text in the Content

Another alternative is to set the ReasonPhrase instead.

Which one is the best way / convention? Set Content or set ReasonPhrase ?

The error message should be put in response body ( Content ), not in response Reason Phrase .

According to RFC 2616

The Reason-Phrase is intended to give a short textual description of the Status-Code...The client is not required to examine or display the Reason-Phrase.

Some explanation:

  1. Reason-Phrase is short , textual description of Status-Code , it should describe Status Code itself, not custom error message. If custom error message is very long, or the message has JSON structure, using Reason-Phrase certainly violates the specification.
  2. As the specification indicate, the client (browser) is not required to examine the Reason-Phrase, which means Reason-Phrase may get ignored for some browsers, in some time.

You can use custom error responses and overrides the 404 and any other error you want visit here Spring MVC: How to return custom 404 errorpages?

Create a view and set this code in app/Exception/Handler.php :

/*Render an exception into a response. * * @param \\Illuminate\\Http\\Request $request * @param \\Exception $e * @return \\Illuminate\\Http\\Response

*/

public function render($request, Exception $e)

{

if($e instanceof NotFoundHttpException)

{

    return response()->view('missing', [], 404);

}

return parent::render($request, $e);

}

Set this use to get it working :

use Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException;

For more info you can visit

https://httpd.apache.org/docs/2.4/custom-error.html

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/displaying-a-custom-error-page-cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM