Adding error codes to Django - django

Currently, when an error occurs in my Django application this is what is returned as an error:
{
"name": [
"This field is required."
]
}
I saw that i can specify custom error message like this
Field(error_messages = { 'required': '12' })
I would like to know if it's possible to tell Django to return error codes along plain text error? And not replace it with error_messages. If it's possible, what's the best way to do it?
Something like this would be nice:
{
"name": [
"This field is required."
],
"error_code": 12
}
This way I could translate the various errors in different languages in my client and not on the server.

This question is tagged django-rest-framework. If indeed you're using DRF, you can do this with a custom exception handler.

Related

How to convert array of object(hasMany relationship data) to array of id?

I wanted to get data and show it in UI. Here's how i write to get the "movies" data.
let movies= yield this.store.findAll('movie');
And I log the "movies". As the picture below shows that there's no data for "photos".
Here's the network:
I'm getting data back from hasura like this:
{
"data": {
"movies": [
{
"id": "584db434-5caa-475e-b3ec-e98e742f0030",
"movieid": "abc123",
"description": "Penquins dancing in antactica",
"photos": [
{
"id": "c4d2833a-4896-42b0-ae8b-0ab9fe71d1d4"
},
{
"id": "e04697e3-21fe-4f0e-8012-443f26293340"
}
]
}
]
}
}
But Ember.js can't read and render the relationship data (photos). Is it the "photos" data should be like this?
"photos": [c4d2833a-4896-42b0-ae8b-0ab9fe71d1d4, e04697e3-21fe-4f0e-8012-443f26293340]
How can I convert it in Ember? or in Hasura?
Thanks for updating your question!
Since you're using ember-data, you'll need a custom adapter and serializer to form your data into the format that ember-data is expecting (since there are infinite numbers of ways APIs decide how to structure data).
More information on that can be found here:
https://guides.emberjs.com/release/models/customizing-adapters/
and here: https://guides.emberjs.com/release/models/customizing-serializers/
Your data is fairly well structured already, so conversion should hopefully go well. Comment back if you have issues <3

Adding pages to a multi-column notion database works flawlessly sometimes and gives a validation error sometimes for the same input

Basically, I'm using Postman to send POST requests to
https://api.notion.com/v1/pages
It works for 70% of the times and rest of the times it gives the following error sometimes. That is, for the same input.
{
"object": "error",
"status": 400,
"code": "validation_error",
"message": "body failed validation. Fix one: body.parent.type should be not present, instead was `\"database_id\"`. body.parent.page_id should be defined, instead was `undefined`."
}
Here's how my body starts
{
"parent": {
"type": "database_id",
"database_id": "a94c42320ef04b6a9c1a7e5e73455557"
},
"properties": {
"Title": {
..................
I'm not posting the entire body because it works flawlessly sometimes.
Please help me out. Is there a way to check logs of the requests that come to my page?
First, I found out that type: database_id is not necessary in parent.
I also found out that syntax errors in the payload returns a 400 error:
body failed validation. Fix one: body.parent.type should be not present, instead was `\"database_id\"`. body.parent.page_id should be defined, instead was `undefined`.
In my case, I wrongly added a value in the same level as parent, properties. Like this:
{
"parent": {
"database_id": "<database_id>"
},
"properties": {
...
},
"wrong_value": {}
}
Since the errors are not that specific, check if you made the same misktake like me, and please also double check if the parent you are trying to post to is actually a database, not a page.
The issue was with having "type: database_id" inside "parent" in the request data.
{
"parent": {
"type": "database_id",(REMOVE THIS LINE)
"database_id": "a94c42320ef04b6a9c1a7e5e73455557"
},
"properties": {
"Title": {
..................
After removing "type" it worked fine. Notion needs to update their docs.

How to customize graphql error response format in Appsync?

I am using Appsync for graphql server. and use `$util.error(String, String, Object, Object)
in the response mapping template to response error to clients. However, the error messages clients get looks like below json. There are too many extra information there. What clients really care about is the messageI made this error. How can I response a simple json object like {"errorMessage": "I made this error"}` to clients?
{
"data": {
"getError": null
},
"errors": [
{
"path": [
"getError"
],
"data": null,
"errorType": "ALWAYS_ERROR",
"errorInfo": null,
"locations": [
{
"line": 2,
"column": 3,
"sourceName": null
}
],
"message": "I made this error"
}
]
}
This is the standard error format for GraphQl per specs - describing code, message and where the error occurred. The primary reason you see this complex format is to due to the nature of GraphQL which can return very deeply nested data. It would be extremely hard to deduce where the issue was with a simple message. In something like REST where the response is standardized its easier to provide that kind of message but in qgl, since the user is building essentially a unique query then we have to be much more thorough with the error response.
That being said, you can, in your client, simplify it by grabbing the first error:
if(data.errors) {
console.error(data.errors[0].errorType)
}

Configuring and using structlog with Django

Does anyone use structlog with Django? I'm looking for a code sample how can I integrate Django logging (which is done via standard library), and structlog.
I've tried the code from the "Rendering Using structlog-based Formatters Within logging" example, with only slightest modifications:
# From my settings.py, basically the same code as in the linked example
timestamper = structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S")
pre_chain = [
structlog.stdlib.add_log_level,
timestamper,
]
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": { ... }, # Exactly like in the linked example
"handlers": { ... }, # Ditto, but only "default" handler (no files)
"loggers": {
"django": {
"handlers": ["default"],
"level": "INFO",
},
# I also had "" logger here, with the same config as "django",
# but it's irrelevant for the example purposes.
}
}
# Same as in the example
structlog.configure(
processors=[
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
timestamper,
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
However, I end up with logging errors. This is an excerpt of what happens on a simple GET request that ends up with 404
TypeError: not all arguments converted during string formatting
...
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 152, in get_response
extra={'status_code': 404, 'request': request},
Message: '\x1b[2m2017-05-08 18:34:53\x1b[0m [\x1b[33m\x1b[1mwarning \x1b[0m] \x1b[1mNot Found: /favicon.ico\x1b[0m'
Arguments: ('/favicon.ico',)
I've tried to figure out what exactly goes on but lost my way in the debugger.
Of course, I can use structlog just for application logging, and keep the standard library loggers like they are. However, I want all logging unified, so my application's output would be uniform, ready for parsing.
I'd greatly appreciate a code snippet that shows how to integrate structlog with Django correctly.
It’s most likely this bug that will be fixed in structlog 17.2 that should be released soonish: https://github.com/hynek/structlog/pull/117 (feel free to comment or to try out if it fixes your problem).

Can I define a custom validation with options for Loopback?

Is there a prescribed way to create a custom validator in loopback? As an example, assume that I want to create something like:
Validatable.validatesRange('aProperty', {min: 0, max: 1000})
Please note that I am aware of:
Validatable.validates(propertyName, validFn, options)
The problem I have with validates() is that validFn does not have access to the options. So, I'm forced to hard code this logic; and create a custom method for every property that needs this type of validation. This is undesirable.
Similarly, I am familiar with:
Model.observes('before save', hookFn)
Unfortunately, I see no way to even declare options for the hookFn(). I don't have this specific need (at least, not yet). It was just an avenue I explored as a possible alternative to solve my problem.
Any advice is appreciated. Thanks in advance!
There is a mention of how to do this over at https://docs.strongloop.com/display/public/LB/Validating+model+data
You can also call validate() or validateAsync() with custom validation
functions.
That leads you to this page https://apidocs.strongloop.com/loopback-datasource-juggler/#validatable-validate
Which provides an example.
I tried it out on my own ...
Question.validate('points', customValidator, {message: 'Negative Points'});
function customValidator(err) {
if (this.points <0) err();
}
And since that function name isn't really used anywhere else and (in this case) the function is short, I also tried it out with anonymous function:
Question.validate('points',
function (err) { if (this.points <0) err(); },
{message: 'Question has a negative value'})
When points are less than zero, it throws the validation error shown below.
{
"error": {
"name": "ValidationError",
"status": 422,
"message": "The `Question` instance is not valid. Details: `points` Negative Points (value: -100).",
"statusCode": 422,
"details": {
"context": "Question",
"codes": {
"points": [
"custom"
]
},
"messages": {
"points": [
"Negative Points"
]
}
What you are looking for is validatesLengthOf(). For example:
Validatable.validatesLengthOf('aProperty', {min: 0, max: 1000});
Here is the documentation links:
All the methods of Validatable class and
Model-wise validation.