mongodb 节点js处理授权错误

omvjsjqw  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(113)

I have a project, and I'm using Node js as a backend. I have a problem with catching errors related to Authorization 401. In case of an Error of type authorization, I'd like to return an object with a message and use it as a middleware, but it doesn't work.
I'm still receiving Html error instead of object.

Authorization Handler:

function handler(err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        // jwt authentication error
        return res.status(401).json({success: false, message: "The user is not authorized"})
    }
    next();
}

module.exports = handler;

App.js: calling the middleware:

const handler=require('./helpers/error-handler');
 
app.use(handler);

Db Handler: handle errors related to database

"use strict";

/**
 * Get unique error field name
 */
const uniqueMessage = error => {
    let output;
    try {
        let fieldName = error.message.substring(
            error.message.lastIndexOf(".$") + 2,
            error.message.lastIndexOf("_1")
        );
        output =
            fieldName.charAt(0).toUpperCase() +
            fieldName.slice(1) +
            " already exists";
    } catch (ex) {
        output = "Unique field already exists";
    }

    return output;
};

/**
 * Get the erroror message from error object
 */
exports.errorHandler = error => {
    console.log('=================================================================')
    console.log(error);
    console.log('=================================================================')

    let message = "";
    // if (error.name==="UnauthorizedError"){
    //     message=error.name + ": " + error.message;
    // }
    if (error.code) {
        switch (error.code) {
            case 401:
                message="User not authorized";
                break;
            case 11000:
            case 11001:
                message = uniqueMessage(error);
                break;
            default:
                message = "Something went wrong";
        }
    } else {
        for (let errorName in error.errorors) {
            if (error.errorors[errorName].message)
                message = error.errorors[errorName].message;
        }
    }

    return message;
};
pkwftd7m

pkwftd7m1#

为什么要使用switch语句和for循环,更好方法是创建一个继承自错误对象的类!

相关问题