简体   繁体   English

django在某处引发异常

[英]django raise the exception somewhere

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.associate_by_email',
)

by using the above code in settings.py i can avoid... 通过在settings.py使用以上代码,我可以避免...

(1062, "Duplicate entry 'example@example.com' for key 'email'") error message. (1062, "Duplicate entry 'example@example.com' for key 'email'")错误消息。

But i searched online and i found this handy code to throw exception in desired html page: 但是我在线搜索,发现这个方便的代码在所需的html页面中引发了exception

[Code 1]: #backends.py [代码1]: #backends.py

class MySocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
    def process_exception(self, request, exception):
        msg = None
        if #no duplicate email:
            return HttpResponse("# catched exception")
        else:
            # processing msg here
            return render_to_response(# html, {msg}, context)

# settings.py #settings.py

MIDDLEWARE_CLASSES = (
    'frontend.backends.MySocialAuthExceptionMiddleware'
)

My problem is solved by based on the above code. 我的问题是根据上述代码solved的。 But in previously i worked with another one functionality with the following code and it is entirely different from the above concept. 但是在以前,我使用以下代码处理了另一个功能,它与上述概念完全不同。

[Code 2]: [代码2]:

def function(request):
    #actual code here
    return HttpResponse('msg here')

But while running the above code, and i got the error message like, 但是在运行上面的代码时,我收到了类似的错误消息,

tuple index out of range in this MySocialAuthExceptionMiddleware .. MySocialAuthExceptionMiddleware tuple index out of range

Actually this is not correct error message for the above code.. This message is related to the code of " [Code 1] ". 实际上,对于上述代码,这不是正确的错误消息。此消息与代码“ [代码1] ”有关。

Then, how can i get the actual error message for " [Code 2] ". 然后,如何获得“ [代码2] ”的实际错误消息。

You don't need to go through all this headache. 您无需经历所有这些头痛。 Exceptions are not special in django, they are part of Python. 异常在django中并不特殊,它们是Python的一部分。

If you want to raise a custom exception - wherever you want to do so: 如果要引发自定义异常-无论您要在哪里进行:

class MyException(Exception):
    pass

def function(request):
    raise MyException('msg here')

The problem you are facing is that in django, middleware is called on every request , even if the request is not "related" to that middleware. 您面临的问题是,在django中,即使请求与该中间件不“相关”,也要在每个请求上调用中间件。

So when writing middleware you need to keep in mind that it will be called for each and every request and it should handle these cases correctly. 因此,在编写中间件时,请记住,将为每个请求调用该中间件,并且该中间件应正确处理这些情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM