47 lines
1.2 KiB
JavaScript
47 lines
1.2 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Error handling functions for the REST server applications.
|
|
* Notes: This module provides reusable functions to create and handle API errors.
|
|
* It includes functions to create application-specific error objects, throw errors, and handle response errors.
|
|
*
|
|
* However, the error handling logic is just the simplest form of error management.
|
|
* @author: Trung Hoang
|
|
* @version: 1.0.1
|
|
* @date: 2023-10-01
|
|
* @license: proprietary
|
|
* @description: This module provides functions to create and handle API errors.
|
|
*/
|
|
|
|
const { isAppError } = require('./utils/common');
|
|
|
|
function appError(tag) {
|
|
if (!tag)
|
|
return { error: { '.tag': 'unknown_error', text: 'Unknown Error' } }
|
|
else
|
|
return { error: { '.tag': tag } }
|
|
// return { error: { '.tag': tag, text: msg ? msg : '' } }
|
|
}
|
|
|
|
function throwError(tag) {
|
|
throw new Error(tag);
|
|
}
|
|
|
|
function handleResErr(res, err, code = 409) {
|
|
if (!res || typeof res !== "object") return;
|
|
|
|
const _erCode = code;
|
|
const _err = isAppError(err);
|
|
if (_err) {
|
|
res.status(_erCode || 409).send(appError(_err));
|
|
} else {
|
|
res.status(_erCode || 500).send(appError('unknown_error'));
|
|
if (err) console.log(err.stack);
|
|
}
|
|
}
|
|
|
|
|
|
module.exports = {
|
|
throwError, appError, handleResErr
|
|
}
|