better error handling

This commit is contained in:
Pau 2025-04-06 18:38:00 +02:00
parent 7639c02a82
commit 325402eaea
2 changed files with 30 additions and 3 deletions

View File

@ -11,6 +11,10 @@ const errorHandler = (err, environment, message) => {
responseJson.message = message || 'Bad Request'
responseJson.code = 400
break
case 'UNAUTHORIZED':
responseJson.message = message || 'Unauthorized'
responseJson.code = 401
break
case 'FORBIDDEN':
responseJson.message = message || 'Forbidden'
responseJson.code = 403
@ -37,6 +41,19 @@ const errorHandler = (err, environment, message) => {
return responseJson
}
const error400 = () => {
const err = new Error('Bad Request')
err.code = 'BAD_REQUEST'
err.status = 400
}
const error401 = () => {
const err = new Error('Unauthorized')
err.code = 'UNAUTHORIZED'
err.status = 401
return err
}
const error403 = () => {
const err = new Error('Forbidden')
err.code = 'FORBIDDEN'
@ -51,6 +68,13 @@ const error404 = () => {
return err
}
const error409 = () => {
const err = new Error('Conflict')
err.code = 'CONFLICT'
err.status = 409
return err
}
const error422 = (message = 'Unprocessable Entity') => {
const err = new Error(message)
err.code = 'UNPROCESSABLE_ENTITY'
@ -58,4 +82,4 @@ const error422 = (message = 'Unprocessable Entity') => {
return err
}
export { error403, error404, error422, errorHandler }
export { error400, error401, error403, error404, error409, error422, errorHandler }

View File

@ -11,6 +11,10 @@ const sendResponseNoContent = (result, req, res) => {
res.status(204).json(result)
}
const sendResponseConflict = (res, err) => {
res.status(409).json(err)
}
const sendResponseServerError = (res, err) => {
res.status(500).json(err)
}
@ -42,7 +46,6 @@ const sendUnprocessableEntityResponse = (res, environment, err = error422()) =>
const sendLoginSuccessfullResponse = (result, req, res) => {
res.status(201).json(result)
console.warn(`User ${result.user._data.username} has logged in`)
}
export { sendLoginSuccessfullResponse, sendCreatedResponse, sendResponseAccessDenied, sendOkResponse, sendResponseBadRequest, sendResponseNoContent, sendResponseNotFound, sendResponseServerError, sendResponseUnauthorized, sendResponseUnprocessableEntity, sendUnprocessableEntityResponse }
export { sendResponseConflict, sendLoginSuccessfullResponse, sendCreatedResponse, sendResponseAccessDenied, sendOkResponse, sendResponseBadRequest, sendResponseNoContent, sendResponseNotFound, sendResponseServerError, sendResponseUnauthorized, sendResponseUnprocessableEntity, sendUnprocessableEntityResponse }