通用异常e捕获将覆盖特定的异常Java

时间:2018-07-05 09:59:00

标签: java web-services exception exception-handling try-catch

throw new ResponseError(new DefaultResponse)中产生错误时,我抛出了一个异常,当我输出消息时看起来很好,但是随后被catch(Exception e)块覆盖了。如果在通用catch上方产生错误,该怎么办?

这是我的网络服务

@DELETE
@SecureIt
@Consumes(value = { MediaType.APPLICATION_JSON })
@Produces(value = { MediaType.APPLICATION_JSON })
@Path("/training-courses/{emptcId}")
@ApiOperation(value = "Delete training course",
              response = DefaultResponse.class,
                authorizations = {
                    @Authorization(
                        value="Bearer" 
                    )
                })
public Response deleteTrainingCourse(@ApiParam(value = "Employee Training Course Id", required = true) @PathParam("emptcId") Integer emptcId,
                                     @Context ContainerRequestContext crc)
throws ResponseError {
    ClsConnectionData connection = null;

    try 
    {
        String mToken = crc.getProperty("token").toString();
        connection = new ClsConnectionData(mToken);

        StatementWrapper sw = new StatementWrapper(connection)
            .createCall(" {CALL j2_employee.delete_training_course(?,?)} ")
            .bind(1,emptcId)
            .registerOutParameter(2, OracleTypes.CURSOR)
            .invoke();

        VoidResult voidResult = (VoidResult)sw.getSingleResultClass(2,VoidResult.class);

        if(voidResult.errorGenerated()) {
            throw new ResponseError(new DefaultResponse(ErrorCodes.DRIVEERROR.code(),
                                                        ResponseType.ERROR.getType(),
                                                        voidResult.getMessage(),
                                                        null));
        //At this point we are throwing the exception
        }
    }
    catch(Exception e)
    {
        //At the end this error is thrown
        System.out.println("Exception e = " + e);
        throw new ResponseError(e,true);
    }
    finally{
      connection.disconnect();
    }

    DefaultResponse dt = new DefaultResponse("0",
                                            ResponseType.SUCCESS.getType(),
                                            "",
                                            null); 
    return Response.ok(dt).build();
}

2 个答案:

答案 0 :(得分:2)

如果要对常规异常进行特殊处理以区别于自定义异常,则...

  

..然后您必须首先捕获...(自定义)异常! ...然后捕获更笼统的...。

赞:

// ...
catch (ResponseError respErr) {
    System.out.println("ResponseError e = " + respErr);
    // re-throw! - no "new"!
    throw respErr;
}
catch (Exception e) {
    // but as @mndeveci mentioned: no good style!
    System.out.println("Exception e = " + e);
    throw new ResponseError(e, true);
}
// ...

答案 1 :(得分:2)

catch(Exception e)捕获任何类型为Exception.class的Exception或try块中抛出的Exception的子类。因此,您也将自己丢入了try块。如果ResponseError是Exception的子类,那么也会被捕获。

您可以将ResponseError丢在尝试之外。如果您在尝试之前定义voidResult并在之后检查errorGenerated,则将不再遇到该问题。你会得到这样的东西:

VoidResult voidResult = null;
try {
    // some code getting to a voidResult
} catch (Exception e) { 
    // some code dealing with this eception
}
if (voidResult != null && voidResult.errorGenerated()) {
    // throw ResponseError
}

或者您应该确保catch(Exception e)不会捕获所有异常,而只能捕获更具体的异常。如果可以的话,取决于实现代码。假设您的实现代码仅引发ConnectionExceptions(举一个例子),则可以捕获(ConnectionException)而不是Exception。如果ResponseError是Exception的子类,但不是ConnectionException的子类,则将不再捕获它。

您还可以执行以下操作:

DefaultResponse errorResponse = null
try {
    // some code
    if (voidResult.errorGenerated()) {
        errorResponse = new DefaultResponse();
    }
} catch (Exception e) { 
    // deal with error
}
if (errorResponse != null) {
    throw new ResponseError////

最后,您可以尝试查看捕获的异常是否是您自己的异常,然后将其重新抛出。

catch (Exception e) {
    if (e instanceof ResponseError && ((ResponseError) e).getCode.equals(myCode)) {
    throw e;
    else { // etc.