DAO的类级别错误处理程序

时间:2018-07-04 16:38:02

标签: c# .net entity-framework error-handling

我正在使用实体框架。下面是ActorsDao类中Actors上下文的列表方法示例。如果您认为我的应用程序就像imdb,那么将有针对各种其他上下文的CRUD方法,例如电影,导演,类型,评论,工作室等。

无论方法或上下文如何,我都以相同的方式处理错误。由于我在多种情况下使用了许多方法,因此我的catch部分始终完全相同。

很明显,我可以创建一个错误处理类,将代码放入其中,然后从catch块中调用该类中的方法。

但是,我想知道是否有一种方法可以从每个方法中省略TRY ... CATCH并为我的实体框架层中的方法设置一个全局错误处理程序?

我只希望此全局错误处理程序处理这些错误,而不处理应用程序其余部分的错误。

我似乎记得在Java Spring中,您可以使用方法名称来注释一个类或方法,并且所有错误都将传递给该类或方法,而无需TRY ... CATCH。我想知道.NET是否有类似的东西(或具有这种功能的第三方库)?

    public List<Actor> ListActors()
    {

        List<Actor> actorList = new List<Actor>();

        using (var context = new ActorContext())
        {
            try
            {
                actorList = context.Actors.ToList<Actor>();

            }
            catch (Exception e)
            {
                //Handle error code
            }
        }

        return actorList;

    }

编辑

我做了进一步的研究,并从这里https://stackoverflow.com/a/4851985/1753877

找到了这段代码
private void GlobalTryCatch(Action action)
{
    try
    {
        action.Invoke();
    }
    catch (ExpectedException1 e)
    {
        throw MyCustomException("Something bad happened", e);
    }
    catch (ExpectedException2 e)
    {
        throw MyCustomException("Something really bad happened", e);
    }
}

public void DoSomething()
{
    GlobalTryCatch(() =>
    {
        // Method code goes here
    });
}

使用这样的委托可以吗?当然可以满足我的要求。

1 个答案:

答案 0 :(得分:0)

您可以创建一个此类,并从该类扩展控制器。

错误处理程序类如下:

package com.wes.essex.rest;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.wes.essex.bean.ErrorResponse;

public class SkyNewsController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkyNewsController.class);

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleError(Exception ex) {
        LOGGER.info("start");
        LOGGER.error(ex.getMessage(), ex);
        ErrorResponse error = new ErrorResponse();
        error.setTimestamp(ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT));
        LOGGER.debug("error : {} ", error);
        ResponseEntity<ErrorResponse> response = null;
        if (ex instanceof ConstraintViolationException) {
            error.setReasonCode(HttpStatus.BAD_REQUEST.value());
            ConstraintViolationException constraintException = (ConstraintViolationException) ex;
            Set<ConstraintViolation<?>> set = constraintException.getConstraintViolations();
            String errorMessage = "Input Validation Failed:";
            for (ConstraintViolation<?> constraintViolation : set) {
                errorMessage += constraintViolation.getMessageTemplate() + ",";
            }
            errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
            error.setErrorMessage(errorMessage);
            response = new ResponseEntity<ErrorResponse>(error, HttpStatus.BAD_REQUEST);
        } else {
            error.setReasonCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            error.setErrorMessage(ex.getMessage());
            response = new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response;
    }
}

这将是错误响应的baean类:

package com.wes.essex.bean;

public class ErrorResponse {

    private static final long serialVersionUID = 5776681206288518465L;

    private String timestamp;
    private String errorMessage;
    private int reasonCode;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public int getReasonCode() {
        return reasonCode;
    }

    public void setReasonCode(int reasonCode) {
        this.reasonCode = reasonCode;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }
}
相关问题