You must Sign In to post a response.
  • Category: ASP.NET

    Web api2 to to throw exception to client

    API Code:
    [HttpPost]
    [Route("Upload")]
    public HttpResponseMessage Upload([FromBody]FileUpload objFileUpl)
    {
    try
    {
    var AttachmentInfoResult = PLMRepository.PlmFileUpload(objFileUpl);
    return Request.CreateResponse(HttpStatusCode.OK, AttachmentInfoResult);
    }
    catch (Exception ex)
    {
    WriteToLog(ex);
    return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message.Replace("ERROR: ", ""));
    }
    }
    MVC controller:


    [HttpPost]
    public JsonResult FilesUpload()
    {
    try
    {

    return this.Json(objAtList, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
    WriteToLog(ex, "UploadController");
    throw;
    }

    Here in above exception in api should be thrown to mvc controller from where the api was triggered
  • #765158
    Hi,
    Try this:
    catch (Exception ex)
    {
    HttpError myCustomError = new HttpError("Custom error message: "+ ex.Message.Replace("ERROR: ", "")) { { "CustomErrorCode", 1 } };
    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError);
    }

    Results recieved in response is as follows:
    {
    "Message": "Custom error message: XYZ",
    "CustomErrorCode": 1
    }
    Hope it helps.
    Regards,
    Shashikant Gurav
    shashikantgurav22@gmail.com


Sign In to post your comments