django-rest-framework custom error message as response - error-handling

For my API, I need to respond every request's error with HTTP 200 and a JSON content. So instead of, responding with this:
Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I'd like to do this:
res = {"code": 400, "message": "Bad Requset"}
Response(res)
Where is the best place to put such thing and how? In Serializer, Renderer, Exception? I need to catch every exception that serializer might throw as well as custom exception that I have written.

You may use status code 200 and with data=json.dumps(...), something like this:
res = {"code": 400, "message": "Bad Requset"}
return Response(data=json.dumps(res), status=status.HTTP_200_OK)
In terms of where to handle the exception, RestFramework has it covered, read Exceptions - Django REST framework, you can create a custom handler and do so.
However as api end points normally will be per view base, I would personally recommend create a custom decorator to wrap your views and return such Response in case of error.
Or, if you really want to return same response on ALL errors, then follow RestFramework doc and customise your error handling should be the best practice.
Hope this helps.

Related

api request problem response 500 from backend

All welcome, I ran into a problem in which at the time of passing id and body in the method it is received, it gives 500 errors. In swagger I have an infected method, it looks like this:
swagger
Accordingly, in the body of the request, I pass all the parameters of the fields it needs (I drive them in strictly, just to check for operability):
code
In response I get this:
response
If you try to do the same in the swagger, then the method works and a 200 response comes:
swagger 200 response
What am I doing wrong?
I tried to make the code asynchronous, I tried to pass fields in different ways, but nothing happens, the answer comes 500
Try to put the id field inside the obj.
const form = {
id: 790,
...
}
You are passing too much params inside the callback (id, form).

Override default JsonSerializer on serialize exception

Is it possible, to override default Net.Core JsonSerializer or catch Exception on serialize?
Actually, when i pass wrong field type to model, required in controler(for example property is type of string i will pass int) then response look like this
{
"status": 400,
"message": "Validation error",
"data": [ {
"filedName": "$.Username",
"validateErrors": ["The JSON value could not be converted to System.String. Path: $.Username | LineNumber: 0 | BytePositionInLine: 16."]
}]
}
when i print this message to user, he won't know what i'm talking about. I need to ovveride this message for "Value is incorrect. Required [type]"
I have custom Provider which implement IValidationMetadataProvider to customize response on model validation error, but those error is not catching there.
You have three options
Catch the Json exception in server middleware, interrogate it, and then convert it to something more succint for the client. Search up "app.UseMiddleware<>()".
Inspect the status code of the HttpResponse message on the client, interrogate it, and then convert it to something more succinct for the UI.
Perform rudimentary format / variable type validations on the client before sending to the controller / API.
I would recommend approach 3. The API has presented a contract to you for the payload. The least the client / UI can do is make sure it complies with the contract. Failures due to business logic / rules definitely do belong on the server.

Flask Error: If something fails in the flask backend, how does the error propagate to the front end?

Consider a simple application where a user fills a form to divide two numbers, in the routes the form data is proceeded [made into float] and then passed as parameters to a python script's function that has the division logic.
The logic fails due to division by 0 is handled as a custom message in the terminal. How does one send this custom message back to the front end UI along with a 500 error message? Trying to make a restful flask app here.
So far I can abort and show a custom message but not the one that propagated from the backend. Also looked into custom error handling but I want to writer of the external python script to be able to write the custom message.
You can Flask errorhandler(errorcode) to manage your errors and display those on the frontend.
#app.errorhandler(500)
def code_500(error):
return render_template("errors/500.html", error=error), 500
You can put whatever else you want in the html template.
You can also call the code_500(error) func directly.
Same principle applies for any other HTTP error code if you want to customize the page and the message (401, 403, 404, etc...).
If you're inside a blueprint, you can use app_errorhandler instead.
You could use the abort() function. From the docs:
When using Flask for web APIs, you can use the same techniques as above to return JSON responses to API errors. abort() is called with a description parameter. The errorhandler() will use that as the JSON error message, and set the status code to 404.
You could implement it like this
#app.route("/div")
def divide():
x, y = request.form['x'], request.form['y']
try:
result = x / y
except ZeroDivisionError:
abort(400, description="Your message here")
else:
# Proper response
From there, the important step is properly catching that message on your frontend.

Google Sheet API batchUpdateByDataFilter PHP Function

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdateByDataFilter
We have used above function in our code, while we are passing the more than 50 or 100 records within the array records then given 400 bad request array in response.
Can anyone describe the limit of the total values that we are going to pass within the above function?
Here is my code:
$batchupdate = array("valueInputOption" => "RAW", "data" => $dataarray);
try {
$requestBody = new Google_Service_Sheets_BatchUpdateValuesByDataFilterRequest($batchupdate);
$response = $service->spreadsheets_values->BatchUpdateByDataFilter($spreadsheetId, $requestBody);
}
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
Troubleshooting:
Problems with the Request
Until you attach a sanitized version of your Request body we cannot be sure about the root-cause of the problem you are facing.
However, an error 400 means that the request you did is invalid. So, most likely, the problem is in that.
Check if your request object is formatted as detailed on the documentation.
Problems with the Client
If you are able to use the Try this API sidebar with the same Request Body then it could be related to the PHP client.
Note: This is language independent. Create a JSON Object that has the same structure as your request body.
If that's the case, we will need to see more of your code to verify that you are not using your valid Request body in an invalid way (eg. sending it encapsulated in another object).
By referencing the PHP Library documentation you can see the properties of the objects you can use.

Laravel 5.7 Handle email verification errors from API

I'm using laravel 5.7 to build an API REST.
When I add the verified middleware to my route group and I try to login with an unverified user by my client api, I get the error 400 Bad request. This error is too generic and don't show the problem clearly for my customer (it's happens in a login form).
If I to edit the render() method in Handler.php to ignore the isApiCall() and return parent::render($request, $e);, so I get the full error (Your email address is not verified, status 403), but when I try to return this in a json object with response()->json([$e]), the response is always empty.
So how to handle properly the api errors to be return the full message from exception, in this case?
You probably have already solved this problem, but this solution might help someone else:
The reason why your response was returning an empty array is because you were passing an Exception type object into the json function that is expecting an array. The response should look like this:
return response()->json(['message' => $e->getMessage()]);
This will return a json response like:
{
"message": "Your email address is not verified"
}