我有同样的问题。如果我使用此构造
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error in update");
我的消息未通过 传递给客户端。对我来说,绕过它的唯一方法是创建类JSON
GlobalExceptionHandler
package mypackage;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Date;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorDTO> generateNotFoundException(NotFoundException ex) {
ErrorDTO errorDTO = new ErrorDTO();
errorDTO.setMessage(ex.getMessage());
errorDTO.setStatus(String.valueOf(ex.getStatus().value()));
errorDTO.setTime(new Date().toString());
return new ResponseEntity<ErrorDTO>(errorDTO, ex.getStatus());
}
}
我还创建了自己的类型Exception
package mypackage;
import org.springframework.http.HttpStatus;
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
public HttpStatus getStatus() {
return HttpStatus.NOT_FOUND;
}
}
这样,我就可以从控制器抛出异常,并且我得到了正确的结果 - 我想看到的消息。JSON
@PutMapping("/data/{id}")
public DataEntity updateData(@RequestBody DataEntity data, @PathVariable int id) {
throw new NotFoundException("Element not found");
}
我也不得不介绍ErrorDTO
package mypackage;
public class ErrorDTO {
public String status;
public String message;
public String time;
...
...
// getters and setters are here
...
...
}
更新
正如@Hassan和@cunhaf(在原始问题下的评论中)所提到的,解决方案
server.error.include-message=always
与.尽管如此,如果有人想通过异常传递更多信息,解决方案可能会更好。ResponseStatusException
GlobalExceptionHandler
源码
可在此处找到示例:全局异常处理程序