xxxxxxxxxx
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
rescue ActiveRecord::RecordNotFound
render json: { error: "User not found" }, status: :not_found
end
end
xxxxxxxxxx
#raise exception
raise ValueError('A very specific bad thing happened.')
xxxxxxxxxx
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
xxxxxxxxxx
# Basic syntax:
raise Exception("An error occured")
# Example usage:
# Say you want to raise an error when a file isn't found, you could do:
raise FileNotFoundError("Error, the file you requested wasn't found")
# Note, for a complete list of built-in exceptions, see this documentation:
# https://docs.python.org/3/library/exceptions.html#bltin-exceptions
xxxxxxxxxx
# this raises a "NameError"
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
xxxxxxxxxx
# Raise a built-in exception
raise ValueError("Invalid value entered!")
# Raise a custom exception
class MyCustomException(Exception):
pass
raise MyCustomException("This is a custom exception!")
xxxxxxxxxx
def raise_an_error(error):
raise error
raise_an_error(ValueError)