none
Error Handling in Power Query and M

    Question

  • Hi,

    I have a problem, iam loading data from REST API using Power Query. 

    REST API using autentication in query header, iam calling the API like this to get the SecureToken that iam using later: Source = Web.Contents("https://app.idoklad.cz/developer/api/Agendas/GetSecureToken?username=opla&password=pass"). 

    So when user insert username and password correctly, in response will be hash code. But if it isnt insert correctly, I get an DataSource.Error (400): Bad Request.

    Is there some way in my code to determine if there is an error and if there is then write notice to type correct credentials?

    Thanks for asnwer


    Ondra Plánička


    Tuesday, July 15, 2014 2:38 PM

Answers

  • In theory, error recovery is straightforward. You use the M construction "try expression otherwise recovery". What complicates this a little is that a lot of M library functions do lazy evaluation. Web.Contents is one of these. You can't really say try Web.Contents("http://some_url") otherwise "failed" because Web.Contents won't actually fail. You have to put the try in front of something that will actually force the HTTP request to be made.

    Here's a short code snippet which demonstrates how this can work:

    let
        Source = Web.Contents("http://localhost:5001/foo"),
        Parsed = try Json.Document(Source) otherwise error "Update credentials please"
    in
        Parsed

    Wednesday, July 16, 2014 3:08 AM
    Owner

All replies

  • In theory, error recovery is straightforward. You use the M construction "try expression otherwise recovery". What complicates this a little is that a lot of M library functions do lazy evaluation. Web.Contents is one of these. You can't really say try Web.Contents("http://some_url") otherwise "failed" because Web.Contents won't actually fail. You have to put the try in front of something that will actually force the HTTP request to be made.

    Here's a short code snippet which demonstrates how this can work:

    let
        Source = Web.Contents("http://localhost:5001/foo"),
        Parsed = try Json.Document(Source) otherwise error "Update credentials please"
    in
        Parsed

    Wednesday, July 16, 2014 3:08 AM
    Owner
  • Hi,

    Will the above error handler work if the received JSON document is invalid. 

    Today I checked below query and it fired a run time error

    let
        Source = "{""name"":""John Johnson"",""street"":""Oslo West 16"",""phone"":}",
        jsondoc = try Json.Document(Source) otherwise error "PARSER ERROR"
        
    in
        jsondoc

    The reason is the value for the key "phone" not given. As I included it in custom error handler it should throw "PARSER ERROR". Then why its throwing run time error?


    Antony

    Friday, October 28, 2016 8:16 AM