我想实现@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的控制器中,以下方法签名按预期工作(返回{“error”:invalid 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);
}
}
}
答案 0 :(得分:0)
我知道已经有一段时间了,但是我相信您在控制器类中缺少@Validated
注释。
import org.springframework.validation.annotation.Validated;
@Validated // class level
public class BaseController {
//...
}