error-handle.js 1.25 KB
/**
 *
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 16/8/3
 */

async function errorHandle(err, ctx) {
    let code = err ? 500 : ctx.response.status;
    let message = err ? err.toString() : ctx.response.message;

    switch (ctx.accepts('json', 'html', 'text')) {
        case 'json':
            ctx.body = {
                code: code,
                message: message
            };

            break;
        case 'html':
            await ctx.render('action/500', {error: err.stack || err});
            break;
        default:
            break;
    }
}

function statusHandle(ctx) {
    let status = ctx.response.status;

    if (status === 404) {
        switch (ctx.accepts('json', 'html', 'text')) {
            case 'json':
                ctx.body = {
                    code: status
                };

                break;
            case 'html':
                ctx.redirect('/' + status);
                break;
            default:
                break;
        }
    }
}

export default function(app) {

    return async function(ctx, next) {
        try {

            await next();
            statusHandle(ctx);
        } catch (err) {
            console.error(err.stack || err);
            await errorHandle(err, ctx);
        }
    };
}