2015-01-23 4 views
2

Sails.js을 사용하여 REST API 서버를 개발하고 있습니다. 사용의 편의를 위해 Sails.js의 예외 처리

는 추상화 위해 나는 나의 컨트롤러의 내부 예외를 던지고 싶습니다 예 :

// api/controllers/TempController.js 

module.exports = { 
    index: function(request, response) { 

    throw new NotFoundException('Specific user is not found.'); 

    throw new AccessDeniedException('You have no permissions to access this resource.'); 

    throw new SomeOtherException('Something went wrong.'); 

    } 
}; 

나는 (글로벌 수준에) 자동으로 그 예외를 포착하고로 변환하려면 어떻게 유효한 JSON 응답? 예컨대 :

가 내장 사용하는 등의 예외를 처리하기 위해 serverError 응답 최선의 방법
{ 
    "success": false, 
    "exception": { 
    "type": "NotFoundException", 
    "message": "Specific user is not found." 
    } 
} 

인가? 또는 사용자 지정 미들웨어를 만드는 것이 더 좋습니까? 그렇다면 간단한 예제를 제공 할 수 있습니까?

답변

2

처리되지 않은 예외는 첫 번째 인수 data으로 api/responses/serverError.js의 기본 응답으로 전달됩니다. 여기

는 예외 처리하는 방법의 예 :

예외 제어기에서 발생되는
var Exception = require('../exceptions/Exception.js'); 

module.exports = function serverError (data, options) { 

    var request = this.req; 
    var response = this.res; 
    var sails = request._sails; 

    // Logging error to the console. 
    if (data !== undefined) { 
    sails.log.error('Sending 500 ("Server Error") response: \n', String(data)); 
    } else { 
    sails.log.error('Sending empty 500 ("Server Error") response'); 
    } 

    response.status(500); 

    if (data instanceof Exception) { 
    return response.json({ 
     success: false, 
     exception: { 
     type: data.constructor.name, 
     message: data.message 
     } 
    }); 
    } else { 
    return response.json(data); 
    } 
}; 

:

// api/controllers/TempController.js 

var NotFoundException = require('../exceptions/NotFoundException.js'); 

module.exports = { 
    index: function(request, response) { 

    throw new NotFoundException('Specific user is not found.'); 

    } 
}; 

이 출력 할 것이다 다음 JSON :

{ 
    "success": false, 
    "exception": { 
     "type": "NotFoundException", 
     "message": "Specific user is not found." 
    } 
}