Pau*_*aul 26 java spring spring-mvc
我有一个自定义的异常类注释返回给定HttpStatus:
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid parameter")
public class BadRequestException extends RuntimeException
{
public BadRequestException(String msg)
{
super(msg);
}
}
Run Code Online (Sandbox Code Playgroud)
当我BadRequestException从我的控制器中抛出一个但是原因总是"无效的参数"当然有效.有没有办法在这个类中设置返回的原因?我想传递一个字符串作为原因.
谢谢!
Ran*_*ndy 14
如果在自定义异常的@ResponseStatus注释中省略'reason'属性,
@ResponseStatus(value = HttpStatus.CONFLICT) // 409
public class ChildDataExists extends RuntimeException {
...
Run Code Online (Sandbox Code Playgroud)
然后抛出异常
throw new ChildDataExists("Can't delete parent if child row exists.");
Run Code Online (Sandbox Code Playgroud)
异常消息作为JSON输出中"数据"的"消息"传递.注释中的"原因"似乎会覆盖自定义行为.
Boz*_*zho 12
您可以使用 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid foo");
ger*_*tas 11
正确的方法是在控制器中引入异常处理程序,然后可以设置任何状态代码的响应主体:
@Controller
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class SomeController {
...
@ExceptionHandler(BadRequestException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
Map<String,Object> handleIndexNotFoundException(BadRequestException bre,
HttpServletRequest request, HttpServletResponse resp) {
HashMap<String, Object> result = new HashMap<>();
result.put("error", true);
result.put("error_message", bre.getMessage());
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
移过您不必使用任何Spring Web MVC注释和依赖项污染您的模型/异常类.
如果你想与所有控制器共享处理程序,请查看@ControllerAdvice.
从 spring 5.0 开始,您可以使用ResponseStatusException可用的
Run Code Online (Sandbox Code Playgroud)// From https://www.baeldung.com/spring-response-status-exception @GetMapping("/actor/{id}") public String getActorName(@PathVariable("id") int id) { try { return actorService.getActor(id); } catch (ActorNotFoundException ex) { throw new ResponseStatusException( HttpStatus.NOT_FOUND, "Actor Not Found", ex); } }
| 归档时间: |
|
| 查看次数: |
14493 次 |
| 最近记录: |