How to return 404 when resource is not found, instead of HTML

I have this controller:

# frozen_string_literal: true

class MetricsController < ApplicationController
  before_action :set_post, only: [:update]

  def update
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  private

  def set_post
    @post = Post.find_by(site: params[:site_id], post_id: params[:post_id])
  end

  def post_params
    params.fetch(:post, {})
  end
end

And I would like to know how can I return 404 not found when @post is nil. Right now @post.update raises an error if @post is nil, and the response is a HTML.


You could make use of ActiveRecord::FinderMethods#find_by! which raises an ActiveRecord::RecordNotFound instead of nil when the record isn't found, and then use a rescue_from block to handle the error.

class MetricsController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound do |exception|
    # it is up to you create RecordNotFoundSerializer
    serializer = RecordNotFoundSerializer.new exception

    render json: serializer.to_json, status: :not_found
  end

  private

  def set_post
    @post = Post.find_by(site: params[:site_id], post_id: params[:post_id])
  end
end

You can also extract the error handling to a base controller (ApplicationController in you example) and centralize error handling there.

How do you return 404 when resource is not found in Django REST , but if a user goes to 127.0.0.1:8000/snip They get the html formatted error rather than a json formatted error. share. 1:49. Retry the web page by pressing F5, clicking/tapping the refresh/reload button, or trying the URL from the address bar again. The 404 Not Found error might appear for several reasons even though no real issue exists, so sometimes a simple refresh will often load the page you were looking for.


You can add a check and return not_found if @post is nil & inorder to prevent your app from crashing you can handle other errors by adding rescue block and return your desired from there

def update
 return render json: YOUR_ERROR, status: :not_found unless @post
 if @post.update(post_params)
   render json: @post
 else
   render json: @post.errors, status: :unprocessable_entity
 end
rescue StandardError => e
  render json: e, status: :unprocessable_entity
end

Should I return a 204 or a 404 response when a resource is not found?, http://example.com/logs/2015-05-19 would return HTTP 404 , which means ( https://jersey.java.net/apidocs/2.6/jersey/javax/ws/rs/NotFoundException.html). You are attempting to access a resource ( /eventscheduler/ ) that does not exist. Of course, you may just want to return a generic 500 error instead of a specific � Yes, it is pretty common to return 404 for a resource not being found. Just like a web page, when it's not found, you get a 404. It's not just REST, but an HTTP standard. Every resource should have a URL location. URLs don't need to be static, they can be templated. So it's possible for the actual requested URL to not have a resource.


You can add a check for @post to your controller action and return a 404 if it's nil:

def update
  if @post
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  else
    render json: YourCustomJsonError, status: 404
  end
end

404 Not Found Error: What It Is and How to Fix It, An in-depth explanation of what a 404 Not Found Error response code is, code , which indicates that the requested resource could not be found. such as HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. “ belong” to the extension itself, but are instead created and managed by� If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead. 10.4.5 404 Not Found. The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.


How to correctly return the HTTP status code 404 for an error page , foremost, a page that informs the user that the requested resource does not exist. How does Google handle “not found” pages that don't return a 404? create an error page (404.html or 404.php) on the first level of the 'page not found' pages that are returning a 200 response code instead of a 404? If the file is handled by aspnet_isapi.dll, you can enable CustomErrors in web.config file and redirect user to 404 page when error state code is 403. For example: <customErrors mode="On"> <error statusCode="403" redirect="Not Found.htm" /> </customErrors> I look forward to receiving your test results.


HTTP 404, The HTTP 404, 404 Not Found, 404, Page Not Found, or Server Not Found error message is a HTTP status code indicating that the resource was not found Some websites report a "not found" error by returning a standard web page with a path (e.g. http://example.com/error.html) rather than a relative path (/error.html). description The requested resource (/Beer-v1/result.jsp) is not available. This app is running when I replace the "result.jsp" as given in the book with a "hello.jsp" given in one of the examples provided in TOMCAT.


Error Response: Use status code 404 for "resource not found" � Issue , Error Response: Use status code 404 for "resource not found" #54 Right, because the URL is not part of the request uri but rather the request headers to explicitly not do that: https://tools.ietf.org/html/rfc7234#section-4.2.2� For this, we need to download and import flask. Download flask through the following commands on CMD. pip install flask. Using app.py as our Python file to manage templates, 404.html be the file we will return in the case of a 404 error and header.html be the file with header and navbar of a website. app.py.