package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.http.ProblemDetail;
import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ResponseStatus;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(DemoApplication.class);
		java.util.Map<String, Object> props = new java.util.HashMap<>();
		props.put("spring.mvc.problemdetails.enabled", "true");
		props.put("server.error.whitelabel.enabled", "false");
		app.setDefaultProperties(props);
		app.run(args);
	}

	@RestController
	class HelloController {

		@GetMapping("/hello")
		public String sayHello() {
			throw new RuntimeException("Simulated error");
		}
	}

	@ControllerAdvice
    public static class MyResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

		@ExceptionHandler(Exception.class)
		public ResponseEntity<Object> handleRuntimeException(Exception ex, WebRequest request) {
			ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
			problemDetail.setTitle("OH NOOOOO :(");
			problemDetail.setDetail(ex.getMessage());
			problemDetail.setProperty("customProperty", "Custom Value");
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetail);
		}
	}

}

