当前位置: 首页 > 知识库问答 >
问题:

ExceptionHandler,获取java。lang.IllegalStateException:无法解析索引0处的方法参数?

毛德华
2023-03-14

我对Java Spring的ExceptionHandler有一个问题。我有一个名为EntityNotFoundException的异常,我希望在引发异常时从REST控制器调用ExceptionHandler方法。

这是我的REST控制器方法代码:

@ExceptionHandler(Exception.class)
public ResponseEntity insertTicket(@Valid @RequestBody Ticket ticket, @AuthenticationPrincipal Principal principal) throws EntityNotFoundException {
    ticket.setCreationTimestamp(Instant.now());
    ticket.setSource(TicketSource.CLIENT);
    ticket.setCurrentTicketStatus(TicketStatus.VALIDATION);
    User customer = userController.findUserByUsername(principal.getName());
    ticket.setCustomer(customer);
    try {
        ticket.setAttachments(savedFiles(
                ticket.getAttachments(),
                ticket.getCustomer().getUsername()
        ));
    } catch (FileUploadException e) {
        return CommonResponseEntity.NotFoundResponseEntity("ENTITY_NOT_FOUND");
    }
    ticketController.insertTicket(ticket);

    mailSenderController.sendMail(customer.getEmail(), "TICKET_OPENED");

    return CommonResponseEntity.CreatedResponseEntity("CREATED");
}

这是我的异常处理程序代码

@EnableWebMvc
@ControllerAdvice
@RestControllerAdvice
public class InterceptedResponseEntityExceptionHandler extends 
   ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    BindingResult bindingResult = ex.getBindingResult();

    List<MethodArgumentFieldError> methodArgumentFieldErrors = bindingResult
            .getFieldErrors()
            .stream()
            .map(fieldError -> new MethodArgumentFieldError(fieldError.getField(), fieldError.getCode(), fieldError.getRejectedValue()))
            .collect(Collectors.toList());

    List<MethodArgumentGlobalError> methodArgumentGlobalErrors = bindingResult
            .getGlobalErrors()
            .stream()
            .map(globalError -> new MethodArgumentGlobalError(globalError.getCode()))
            .collect(Collectors.toList());

    MethodArgumentError methodArgumentError = new MethodArgumentError(methodArgumentFieldErrors, methodArgumentGlobalErrors);

    return new ResponseEntity<>(methodArgumentError, HttpStatus.UNPROCESSABLE_ENTITY);
}

@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    MissingParameterError missingParameterError = new MissingParameterError(ex.getParameterName(), ex.getMessage());

    return new ResponseEntity<>(missingParameterError, HttpStatus.UNPROCESSABLE_ENTITY);
}



@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleNotFound(Exception ex, WebRequest request) {

    System.out.println("inside!");

    if( ex instanceof DataIntegrityViolationException){
        System.out.println("Data integrity violation");
        String constraintViolationErrors = ex.getMessage();
        String msgErr = (constraintViolationErrors.substring(constraintViolationErrors.indexOf("=") + 1));
        return new ResponseEntity<>(msgErr, HttpStatus.BAD_REQUEST);
    }

    if(ex instanceof UsernameNotFoundException) {
        String msgErr = ex.getMessage();
        return new ResponseEntity<>(msgErr, HttpStatus.BAD_REQUEST);
    }


    if (ex instanceof NotFoundEntityException || ex instanceof EntityNotFoundException || ex instanceof NoSuchElementException){
        //return CommonResponseEntity.NotFoundResponseEntity(ex.getMessage());
        System.out.println("inside the handler!");
        return new ResponseEntity<>(ex.getMessage(),HttpStatus.NOT_FOUND);
    }

    if(ex instanceof  UpdateException){
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    return null;
}





@Data
@AllArgsConstructor
public class MethodArgumentError {
    private List<MethodArgumentFieldError> fieldErrors;
    private List<MethodArgumentGlobalError> globalErrors;
}

@Data
@AllArgsConstructor
public class MethodArgumentFieldError {
    private String field;
    private String code;
    private Object rejectedValue;
}

@Data
@AllArgsConstructor
public class MethodArgumentGlobalError {
    private String code;
}

@Data
@AllArgsConstructor
public class MissingParameterError {
    private String parameterName;
    private String message;
}

@Data
@AllArgsConstructor
public class ConstraintViolationError {
    private String invalidValue;
    private String message;
}

}

我不知道为什么,当我获得DataIntegrityViolationException时,会调用ExceptionHandler,而当我获得EntitynotFoundException时,会收到以下消息:

java.lang.IllegalStateException: Could not resolve method parameter at index 0 in public org.springframework.http.ResponseEntity com.isssr.ticketing_system.rest.TicketRest.insertTicket(com.isssr.ticketing_system.entity.Ticket,java.security.Principal) throws com.isssr.ticketing_system.exception.EntityNotFoundException: No suitable resolver for argument 0 of type 'com.isssr.ticketing_system.entity.Ticket'

有什么问题??

共有1个答案

董俊
2023-03-14

我看到了其他的东西;我收到以下消息:

调用@ExceptionHandler方法失败:public org。springframework。http。ResponseEntity公司。isssr。票务系统。RestTicketRest。insertTicket(com.isssr.ticketing\u system.entity.Ticket,java.security.Principal)抛出com。isssr。票务系统。例外EntityNotFoundException

所以,Spring似乎试图调用另一个方法,而不是我的ExceptionHandler的方法。这怎么可能?

 类似资料: