【问题标题】:springboot exceptionhandling without controller class没有控制器类的spring boot异常处理
【发布时间】:2017-06-16 03:35:09
【问题描述】:

在没有控制器类的情况下,Spring Boot 1.5.4 中如何处理异常处理?目前,我只有以下实体和存储库类。

Task.class:(实体)

@Entity
@Table(name = "task")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Length(min = 1)
    private String name;

    public Task() {

    }

    public Task(String name) {
        this.name = name;
    }

    public Task(Long id, String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName(){
        return name;
    }

}

Repository.class:

public interface TaskRepository extends PagingAndSortingRepository<Task, Long> {
}

POST 方法:返回 200 ok

http://localhost:8080/tasks

{
"name" : "test"
}

但是,

{
"name" : ""
}

返回 500 ,而不是 400 错误。

请告诉我,如果有任何方法可以在没有控制器类的情况下处理此异常。

【问题讨论】:

    标签: spring-boot exception-handling


    【解决方案1】:

    您可以使用带有@ControllerAdvice 注释的全局@ExceptionHandler。基本上,您使用 @ControllerAdvice 注解在类中使用 @ExceptionHandler 定义要处理的异常,然后在抛出该异常时实现您想要执行的操作。

    像这样:

    @ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
    public class GlobalExceptionHandler {
    
        @ExceptionHandler({ValidationException.class, JsonParseException.class})
        public ResponseEntity<Map<String, String>> yourExceptionHandler(Exception e) {
            Map<String, String> response = new HashMap<String, String>();
            response.put("message", "Bad Request");
            return new ResponseEntity<Map<String, String>>(response, HttpStatus.BAD_REQUEST);
        }
    }
    

    另见:http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html

    【讨论】:

    • 我的应用程序中没有任何控制器类。那么,@ControllerAdvice 注释会起作用吗?
    • 谢谢...我添加了异常类,现在可以看到 404 错误。但是,如何为我的以下请求获取正确的错误代码为 400 ?场景:空字符串,不带引号的字符串,空体{ "name" : "" }{ "name" : test }{ }
    • 我能够在这里重现错误,我看到异常是一个 ConstraintViolationException,它是一个 ValidationException... 所以我更新了对 ValidationException 的答案...检查一下
    • 而对于“{}”的情况,您需要在name(任务类)上添加@NotBlank
    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 2021-06-27
    • 2019-10-09
    • 2022-11-29
    • 1970-01-01
    • 2022-11-25
    • 2022-06-19
    • 2023-03-28
    相关资源
    最近更新 更多