Spring 引导约束违规仅当存在@PreAuthorize注释时才调用异常处理程序



>我想实现@PathVariable验证,因此我为所有带有异常处理程序的控制器创建了一个基类:

  public class BaseController {
    @ExceptionHandler(value = { ConstraintViolationException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public RestError handleResourceNotFoundException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations ) {
            strBuilder.append(violation.getMessage());
            strBuilder.append("n");
        }
        strBuilder.deleteCharAt(strBuilder.lastIndexOf("n"));
        return new RestError(strBuilder.toString());
    }
}

在扩展 BaseController 的控制器中,以下方法签名按预期工作(返回 {"错误":无效 id}):

@PreAuthorize("hasRole('ROLE_VISA_ADMIN')")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
ResponseEntity<UserRepresentation> getUser(@Pattern(regexp = Constants.UUID_REGEX, message = "invalid id")
                                           @PathVariable String id

而没有@PreAuthorize的相同方法返回状态代码 500 和消息:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException.好像没有异常处理程序。

我是春季启动的新手,因此任何建议将不胜感激。

编辑

下面是控制器的源代码(它实际上实现了描述 API 的接口):

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserController extends BaseController implements UserApi {
    private IUserService userService;
    @Override
    public ResponseEntity<UserRepresentation> getUser(@PathVariable String id) {
        UserRepresentation userRepresentation = userService.getUserRepresentationById(id);
        if (userRepresentation == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(userRepresentation, HttpStatus.OK);
        }
    }
}
我知道

已经有一段时间了,但我相信您在控制器类中缺少@Validated注释。

import org.springframework.validation.annotation.Validated;
@Validated // class level
public class BaseController {
    //...
}

最新更新