def general_exception( request: Request, exc: Exception, status_code: int = 500, # A status_code in `exc` will take precedence errors: List[OptimadeError] = None, ) -> JSONResponse: debug_info = {} if CONFIG.debug: tb = "".join( traceback.format_exception(etype=type(exc), value=exc, tb=exc.__traceback__)) LOGGER.error("Traceback:\n%s", tb) debug_info[f"_{CONFIG.provider.prefix}_traceback"] = tb try: http_response_code = int(exc.status_code) except AttributeError: http_response_code = int(status_code) try: title = str(exc.title) except AttributeError: title = str(exc.__class__.__name__) try: detail = str(exc.detail) except AttributeError: detail = str(exc) if errors is None: errors = [ OptimadeError(detail=detail, status=http_response_code, title=title) ] response = ErrorResponse( meta=meta_values( url=request.url, data_returned=0, data_available=0, more_data_available=False, **debug_info, ), errors=errors, ) return JSONResponse( status_code=http_response_code, content=jsonable_encoder(response, exclude_unset=True), )
def general_exception( request: Request, exc: Exception, status_code: int = 500, # A status_code in `exc` will take precedence errors: List[OptimadeError] = None, ) -> JSONAPIResponse: """Handle an exception Parameters: request: The HTTP request resulting in the exception being raised. exc: The exception being raised. status_code: The returned HTTP status code for the error response. errors: List of error resources as defined in [the OPTIMADE specification](https://github.com/Materials-Consortia/OPTIMADE/blob/develop/optimade.rst#json-response-schema-common-fields). Returns: A JSON HTTP response based on [`ErrorResponse`][optimade.models.responses.ErrorResponse]. """ debug_info = {} if CONFIG.debug: tb = "".join( traceback.format_exception(type(exc), value=exc, tb=exc.__traceback__)) LOGGER.error("Traceback:\n%s", tb) debug_info[f"_{CONFIG.provider.prefix}_traceback"] = tb try: http_response_code = int(exc.status_code) except AttributeError: http_response_code = int(status_code) try: title = str(exc.title) except AttributeError: title = str(exc.__class__.__name__) try: detail = str(exc.detail) except AttributeError: detail = str(exc) if errors is None: errors = [ OptimadeError(detail=detail, status=http_response_code, title=title) ] response = ErrorResponse( meta=meta_values( url=request.url, data_returned=0, data_available=0, more_data_available=False, **debug_info, ), errors=errors, ) return JSONAPIResponse( status_code=http_response_code, content=jsonable_encoder(response, exclude_unset=True), )