Gilles GNANAGBE
Gilles GNANAGBE

Reputation: 41

How to customize the validation error using django Ninja?

```
@router.post("/addUser", response={200: responseStdr, 404: responseStdr,422: responseStdr})    
def addUser(request, user: userRegister):
    try:
        return 200, {"status": 200,
                     "isError": "True",
                     "data": user,
                     "msg": "user crée avec succès",
                     "method": "POST"}
    except :        
        return  {"status": 201,
                     "isError": "True",
                     "data": "erreur format",
                     "msg": "erreur",
                     "method": "POST"} 
```

I'm getting this error :

```
{
    "detail": [
        {
            "loc": [
                "body",
                "user",
                "last_name"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}
```

How to send a custom message instead of this error when a field is not matching with the expected format ?

Upvotes: 0

Views: 2085

Answers (1)

Mike Johnson
Mike Johnson

Reputation: 745

You can add a custom exception handler. In my case, I had to provide an "error" property for the frontend but I kept the details as well.

@api.exception_handler(ValidationError)
def validation_errors(request, exc: ValidationError):
    error = "Validation failed"
    if exc.errors:
        try:
            loc = exc.errors[0]["loc"][-1]
            msg = exc.errors[0]["msg"]
            if loc == "__root__":
                loc = ""
            else:
                loc = f"{loc}: "
            error = f"{loc} {msg}"
        except Exception:
            logging.exception("Error handling validation error")
    return HttpResponse(
        json.dumps({"error": error, "detail": exc.errors}),
        status=400,
        content_type="application/json",
    )

You can take this and customize it to your needs. Add it wherever your Router is (mine is in urls.py).

Upvotes: 1

Related Questions