Jawaban yang diterima dengan baik banyak membantu saya tetapi saya ingin melewatkan HttpStatusCode di middleware saya untuk mengelola kode status kesalahan saat runtime.
Menurut tautan ini saya mendapat ide untuk melakukan hal yang sama. Jadi saya menggabungkan Jawaban Andrei dengan ini. Jadi kode terakhir saya di bawah ini:
1. Kelas dasar
public class ErrorDetails
{
public int StatusCode { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
2. Jenis Kelas Pengecualian Kustom
public class HttpStatusCodeException : Exception
{
public HttpStatusCode StatusCode { get; set; }
public string ContentType { get; set; } = @"text/plain";
public HttpStatusCodeException(HttpStatusCode statusCode)
{
this.StatusCode = statusCode;
}
public HttpStatusCodeException(HttpStatusCode statusCode, string message) : base(message)
{
this.StatusCode = statusCode;
}
public HttpStatusCodeException(HttpStatusCode statusCode, Exception inner) : this(statusCode, inner.ToString()) { }
public HttpStatusCodeException(HttpStatusCode statusCode, JObject errorObject) : this(statusCode, errorObject.ToString())
{
this.ContentType = @"application/json";
}
}
3. Perkecualian Perkecualian Kustom
public class CustomExceptionMiddleware
{
private readonly RequestDelegate next;
public CustomExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (HttpStatusCodeException ex)
{
await HandleExceptionAsync(context, ex);
}
catch (Exception exceptionObj)
{
await HandleExceptionAsync(context, exceptionObj);
}
}
private Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException exception)
{
string result = null;
context.Response.ContentType = "application/json";
if (exception is HttpStatusCodeException)
{
result = new ErrorDetails() { Message = exception.Message, StatusCode = (int)exception.StatusCode }.ToString();
context.Response.StatusCode = (int)exception.StatusCode;
}
else
{
result = new ErrorDetails() { Message = "Runtime Error", StatusCode = (int)HttpStatusCode.BadRequest }.ToString();
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
return context.Response.WriteAsync(result);
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
string result = new ErrorDetails() { Message = exception.Message, StatusCode = (int)HttpStatusCode.InternalServerError }.ToString();
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return context.Response.WriteAsync(result);
}
}
4. Metode Perpanjangan
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<CustomExceptionMiddleware>();
}
5. Konfigurasikan Metode di startup.cs
app.ConfigureCustomExceptionMiddleware();
app.UseMvc();
Sekarang metode login saya di pengontrol Akun:
try
{
IRepository<UserMaster> obj = new Repository<UserMaster>(_objHeaderCapture, Constants.Tables.UserMaster);
var Result = obj.Get().AsQueryable().Where(sb => sb.EmailId.ToLower() == objData.UserName.ToLower() && sb.Password == objData.Password.ToEncrypt() && sb.Status == (int)StatusType.Active).FirstOrDefault();
if (Result != null)//User Found
return Result;
else// Not Found
throw new HttpStatusCodeException(HttpStatusCode.NotFound, "Please check username or password");
}
catch (Exception ex)
{
throw ex;
}
Di atas Anda dapat melihat apakah saya belum menemukan pengguna kemudian menaikkan HttpStatusCodeException di mana saya telah melewati HttpStatusCode.NotFound status dan pesan khusus di
middleware
catch (ex HttpStatusCodeException)
Diblokir akan dipanggil yang akan melewati kontrol
private Task HandleExceptionAsync (konteks HttpContext, pengecualian HttpStatusCodeException)
.
Tetapi bagaimana jika saya mendapat kesalahan runtime sebelumnya? Untuk itu saya telah menggunakan try catch block yang melempar exception dan akan ditangkap di catch (Exception exceptionObj) block dan akan melewati kontrol ke
Task HandleExceptionAsync (Konteks HttpContext, Pengecualian pengecualian)
metode.
Saya telah menggunakan kelas ErrorDetails tunggal untuk keseragaman.
UseExceptionHandler
middleware?