简体   繁体   中英

how to set response when i am using IActionResult in return type with error message?

enter image description here when try block send error to catch block it throw and response I got at frontend was {status:'error',error:500}. Please explain me what is going when I Re-throw in catch block. Is .NET is set response when I re-throw?

I want to set status message. how can I do?

I want to set status message. how can I do?

Well, you can bind custom status inside BadRequest() or Any other response class result. For instance:

public async Task<IActionResult> DownloadAttachedFile()
        {
            try
            {
                //Your code 
            }
            catch (Exception ex)
            {

                return BadRequest(new { StatusMessage = "Your Messaage", StatusCode = 400 });
            }

       
    }

Note: Here StatusMessage , you can even concat your ex message as well. Can introduce new custom error class. You can also skip StatusCode = 400 because BadRequest itself will return that code but if you want to fetch easily from your frontend you can set as well.

Output:

In your frontend you would get the response as following:

{
    "statusMessage": "Your Messaage",
    "statusCode":  400
}

In addition, you can always customize your response class based on your requirement.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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