Spring Boot自定义异常未在日志中打印

时间:2019-01-09 06:19:01

标签: spring-boot error-handling custom-exceptions

我正在尝试为我的Spring boot REST项目实现自定义异常。自定义异常被调用,但对错误消息的显示方式没有任何影响。

这是我用于自定义错误的POJO:

public class ApiError {
    private HttpStatus status;
    private String message;
    private List<String> errors;

    public ApiError(HttpStatus status, String message, List<String> errors) {
        super();
        this.status = status;
        this.message = message;
        this.errors = errors;
    }

    public ApiError(HttpStatus status, String message, String error) {
        super();
        this.status = status;
        this.message = message;
        errors = Arrays.asList(error);
    }
}

这是我编写的异常处理程序:

@ControllerAdvice
@EnableWebMvc
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        System.out.println("Custom exception!!");
        //List<String> details = new ArrayList<>();
        //details.add(ex.getLocalizedMessage());
        //System.out.println("Localize message:: "+ex.getLocalizedMessage());
        // ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),

        //request.getDescription(false));
        ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR,"Server Error", request.getDescription(false));
        return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

此外,我在控制器中定义了以下方法:

@RequestMapping(value = "/model", params = "number", method = RequestMethod.GET, produces = "application/json")
List<Model> getModel(HttpServletRequest request,@RequestParam(value = "codeNumber") String number) throws Exception{

    List<Model> model = null;
    try {
        model = niiService.getModel(number);
    }catch(RuntimeException e){
        new Exception(e);
    }
    return model;
}

但是,我看到了以下异常,而不是我的自定义POJO:

{
    "timestamp": 1547013989124,
    "status": 500,
    "error": "Internal Server Error",
    "message": "Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.",
    "path": "/model"
}

我原本期望以下JSON结构:

{
    "status": 500,
    "message": "Server Error"
    ..
}

请让我知道,为了以我想要的方式获得错误响应,我缺少什么。

2 个答案:

答案 0 :(得分:1)

您在自定义例外之前缺少throw。 另外,请确保您在控制器内部捕获了正确的异常。

更改

catch (RuntimeException e) {
   //custom exception
    new Exception(e);
} 

收件人

catch (RuntimeException e) {
    //custom exception
    throw new Exception(e);
}

答案 1 :(得分:0)

我错过了将getter和setter添加到APIError类。因此,反应并没有达到我的预期。

相关问题