Error responses
Nest.js has an exception layer, which is responsible for catching unhandled exceptions from request handlers and returning an appropriate response to the client.
A global exception filter handles all exception thrown from request handlers.
HttpException
If an exception thrown from a request handler is a HttpException
, the global exception filter will transform it to the a JSON response.
For example, you can throw an HttpException
from the create()
handler function if the body is not valid as shown.
import
{
Body
,
Controller
,
HttpException
,
HttpStatus
,
Post
}
from
'@nestjs/common'
;
@
Controller
(
'entries'
)
export
class
EntryController
{
@
Post
()
create
(
@
Body
()
entry
:Entry
)
{
if
(
!
entry
)
throw
new
HttpException
(
'Bad request'
,
HttpStatus
.
BAD_REQUEST
);
this
.
entryService
.
create
(
entry
);
}
}
If this exception is thrown, the response would look like this:
{
"statusCode"
:
400
,
"message"
:
...